Merge
authorduke
Wed, 05 Jul 2017 22:05:22 +0200
changeset 40319 b45dd3eb246d
parent 40318 3f7eb1205cee (current diff)
parent 40299 5f3bf5e4f32e (diff)
child 40320 2e83d21d78cd
Merge
hotspot/test/runtime/modules/Visibility/XpatchVisibility.java
hotspot/test/runtime/modules/Xpatch/BasicJarBuilder.java
hotspot/test/runtime/modules/Xpatch/Xpatch2Dirs.java
hotspot/test/runtime/modules/Xpatch/Xpatch2DirsMain.java
hotspot/test/runtime/modules/Xpatch/XpatchDupJavaBase.java
hotspot/test/runtime/modules/Xpatch/XpatchDupModule.java
hotspot/test/runtime/modules/Xpatch/XpatchJavaBase.java
hotspot/test/runtime/modules/Xpatch/XpatchMain.java
hotspot/test/runtime/modules/Xpatch/XpatchTest.java
hotspot/test/runtime/modules/Xpatch/XpatchTestJar.java
hotspot/test/runtime/modules/Xpatch/XpatchTestJarDir.java
hotspot/test/runtime/modules/Xpatch/XpatchTraceCL.java
hotspot/test/runtime/modules/XpatchCDS.java
jdk/src/java.base/share/conf/security/cacerts
jdk/test/sun/security/mscapi/AccessKeyStore.sh
--- a/.hgtags-top-repo	Mon Aug 15 08:28:26 2016 +0200
+++ b/.hgtags-top-repo	Wed Jul 05 22:05:22 2017 +0200
@@ -373,3 +373,4 @@
 b30ae794d974d7dd3eb4e84203f70021823fa6c6 jdk-9+128
 f5902d3841b82cac6e7716a20c24e8e916fb14a8 jdk-9+129
 d94d54a3192fea79234c3ac55cd0b4052d45e954 jdk-9+130
+8728756c2f70a79a90188f4019cfd6b9a275765c jdk-9+131
--- a/common/autoconf/boot-jdk.m4	Mon Aug 15 08:28:26 2016 +0200
+++ b/common/autoconf/boot-jdk.m4	Wed Jul 05 22:05:22 2017 +0200
@@ -305,7 +305,7 @@
   BOOT_JDK_SOURCETARGET="-source 8 -target 8"
   AC_SUBST(BOOT_JDK_SOURCETARGET)
 
-  ADD_JVM_ARG_IF_OK([-Xpatch:foo=bar], dummy, [$JAVA])
+  ADD_JVM_ARG_IF_OK([--patch-module foo=bar], dummy, [$JAVA])
   AC_MSG_CHECKING([if Boot JDK supports modules])
   if test "x$JVM_ARG_OK" = "xtrue"; then
     AC_MSG_RESULT([yes])
--- a/common/autoconf/generated-configure.sh	Mon Aug 15 08:28:26 2016 +0200
+++ b/common/autoconf/generated-configure.sh	Wed Jul 05 22:05:22 2017 +0200
@@ -5095,7 +5095,7 @@
 #CUSTOM_AUTOCONF_INCLUDE
 
 # Do not change or remove the following line, it is needed for consistency checks:
-DATE_WHEN_GENERATED=1470415803
+DATE_WHEN_GENERATED=1470863189
 
 ###############################################################################
 #
@@ -30596,13 +30596,13 @@
 
 
 
-  $ECHO "Check if jvm arg is ok: -Xpatch:foo=bar" >&5
-  $ECHO "Command: $JAVA -Xpatch:foo=bar -version" >&5
-  OUTPUT=`$JAVA -Xpatch:foo=bar -version 2>&1`
+  $ECHO "Check if jvm arg is ok: --patch-module foo=bar" >&5
+  $ECHO "Command: $JAVA --patch-module foo=bar -version" >&5
+  OUTPUT=`$JAVA --patch-module foo=bar -version 2>&1`
   FOUND_WARN=`$ECHO "$OUTPUT" | $GREP -i warn`
   FOUND_VERSION=`$ECHO $OUTPUT | $GREP " version \""`
   if test "x$FOUND_VERSION" != x && test "x$FOUND_WARN" = x; then
-    dummy="$dummy -Xpatch:foo=bar"
+    dummy="$dummy --patch-module foo=bar"
     JVM_ARG_OK=true
   else
     $ECHO "Arg failed:" >&5
--- a/common/autoconf/spec.gmk.in	Mon Aug 15 08:28:26 2016 +0200
+++ b/common/autoconf/spec.gmk.in	Wed Jul 05 22:05:22 2017 +0200
@@ -585,7 +585,7 @@
     jdk.jdeps jdk.javadoc jdk.rmic
 ifeq ($(BOOT_JDK_MODULAR), true)
   INTERIM_OVERRIDE_MODULES_ARGS = $(foreach m, $(INTERIM_OVERRIDE_MODULES), \
-      -Xpatch:$m=$(BUILDTOOLS_OUTPUTDIR)/override_modules/$m)
+      --patch-module $m=$(BUILDTOOLS_OUTPUTDIR)/override_modules/$m)
   INTERIM_LANGTOOLS_ARGS = $(INTERIM_OVERRIDE_MODULES_ARGS)
   JAVAC_MAIN_CLASS = -m jdk.compiler/com.sun.tools.javac.Main
   JAVADOC_MAIN_CLASS = -m jdk.javadoc/jdk.javadoc.internal.tool.Main
--- a/common/conf/jib-profiles.js	Mon Aug 15 08:28:26 2016 +0200
+++ b/common/conf/jib-profiles.js	Wed Jul 05 22:05:22 2017 +0200
@@ -417,7 +417,7 @@
         jtreg: {
             server: "javare",
             revision: "4.2",
-            build_number: "b02",
+            build_number: "b03",
             checksum_file: "MD5_VALUES",
             file: "jtreg_bin-4.2.zip",
             environment_name: "JT_HOME"
--- a/corba/.hgtags	Mon Aug 15 08:28:26 2016 +0200
+++ b/corba/.hgtags	Wed Jul 05 22:05:22 2017 +0200
@@ -373,3 +373,4 @@
 1f093d3f8cd99cd37c3b0af4cf5c3bffaa9c8b98 jdk-9+128
 c3e83ccab3bb1733ae903d681879a33f85ed465c jdk-9+129
 77f9692d5976ae155773dd3e07533616bb95bae1 jdk-9+130
+f7e1d5337c2e550fe553df7a3886bbed80292ecd jdk-9+131
--- a/hotspot/.hgtags	Mon Aug 15 08:28:26 2016 +0200
+++ b/hotspot/.hgtags	Wed Jul 05 22:05:22 2017 +0200
@@ -533,3 +533,4 @@
 22bf6db9767b1b3a1994cbf32eb3331f31ae2093 jdk-9+128
 e96b34b76d863ed1fa04e0eeb3f297ac17b490fd jdk-9+129
 7d54c7056328b6a2bf4877458b8f4d8cd870f93b jdk-9+130
+943bf73b49c33c2d7cbd796f6a4ae3c7a00ae932 jdk-9+131
--- a/hotspot/src/jdk.vm.ci/share/classes/jdk.vm.ci.hotspot/src/jdk/vm/ci/hotspot/HotSpotMethodHandleAccessProvider.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/hotspot/src/jdk.vm.ci/share/classes/jdk.vm.ci.hotspot/src/jdk/vm/ci/hotspot/HotSpotMethodHandleAccessProvider.java	Wed Jul 05 22:05:22 2017 +0200
@@ -109,6 +109,9 @@
             if (!s.getReturnType(CLASS).equals(resultType)) {
                 return false;
             }
+            if (s.getParameterCount(false) != parameterTypes.length) {
+                return false;
+            }
             for (int i = 0; i < s.getParameterCount(false); ++i) {
                 if (!s.getParameterType(i, CLASS).equals(parameterTypes[i])) {
                     return false;
--- a/hotspot/src/jdk.vm.ci/share/classes/jdk.vm.ci.services/src/jdk/vm/ci/services/Services.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/hotspot/src/jdk.vm.ci/share/classes/jdk.vm.ci.services/src/jdk/vm/ci/services/Services.java	Wed Jul 05 22:05:22 2017 +0200
@@ -57,7 +57,7 @@
         if (jvmci != requestorModule) {
             for (String pkg : jvmci.getPackages()) {
                 // Export all JVMCI packages dynamically instead
-                // of requiring a long list of -XaddExports
+                // of requiring a long list of --add-exports
                 // options on the JVM command line.
                 if (!jvmci.isExported(pkg, requestorModule)) {
                     jvmci.addExports(pkg, requestorModule);
--- a/hotspot/src/share/vm/classfile/classLoader.cpp	Mon Aug 15 08:28:26 2016 +0200
+++ b/hotspot/src/share/vm/classfile/classLoader.cpp	Wed Jul 05 22:05:22 2017 +0200
@@ -140,7 +140,7 @@
 PerfCounter*    ClassLoader::_isUnsyncloadClass = NULL;
 PerfCounter*    ClassLoader::_load_instance_class_failCounter = NULL;
 
-GrowableArray<ModuleClassPathList*>* ClassLoader::_xpatch_entries = NULL;
+GrowableArray<ModuleClassPathList*>* ClassLoader::_patch_mod_entries = NULL;
 GrowableArray<ModuleClassPathList*>* ClassLoader::_exploded_entries = NULL;
 ClassPathEntry* ClassLoader::_jrt_entry = NULL;
 ClassPathEntry* ClassLoader::_first_append_entry = NULL;
@@ -685,27 +685,27 @@
 }
 #endif
 
-// Construct the array of module/path pairs as specified to -Xpatch
+// Construct the array of module/path pairs as specified to --patch-module
 // for the boot loader to search ahead of the jimage, if the class being
-// loaded is defined to a module that has been specified to -Xpatch.
-void ClassLoader::setup_xpatch_entries() {
+// loaded is defined to a module that has been specified to --patch-module.
+void ClassLoader::setup_patch_mod_entries() {
   Thread* THREAD = Thread::current();
-  GrowableArray<ModuleXPatchPath*>* xpatch_args = Arguments::get_xpatchprefix();
-  int num_of_entries = xpatch_args->length();
+  GrowableArray<ModulePatchPath*>* patch_mod_args = Arguments::get_patch_mod_prefix();
+  int num_of_entries = patch_mod_args->length();
 
-  assert(!DumpSharedSpaces, "DumpSharedSpaces not supported with -Xpatch");
-  assert(!UseSharedSpaces, "UseSharedSpaces not supported with -Xpatch");
+  assert(!DumpSharedSpaces, "DumpSharedSpaces not supported with --patch-module");
+  assert(!UseSharedSpaces, "UseSharedSpaces not supported with --patch-module");
 
-  // Set up the boot loader's _xpatch_entries list
-  _xpatch_entries = new (ResourceObj::C_HEAP, mtModule) GrowableArray<ModuleClassPathList*>(num_of_entries, true);
+  // Set up the boot loader's _patch_mod_entries list
+  _patch_mod_entries = new (ResourceObj::C_HEAP, mtModule) GrowableArray<ModuleClassPathList*>(num_of_entries, true);
 
   for (int i = 0; i < num_of_entries; i++) {
-    const char* module_name = (xpatch_args->at(i))->module_name();
+    const char* module_name = (patch_mod_args->at(i))->module_name();
     Symbol* const module_sym = SymbolTable::lookup(module_name, (int)strlen(module_name), CHECK);
     assert(module_sym != NULL, "Failed to obtain Symbol for module name");
     ModuleClassPathList* module_cpl = new ModuleClassPathList(module_sym);
 
-    char* class_path = (xpatch_args->at(i))->path_string();
+    char* class_path = (patch_mod_args->at(i))->path_string();
     int len = (int)strlen(class_path);
     int end = 0;
     // Iterate over the module's class path entries
@@ -735,10 +735,10 @@
       }
     }
 
-    // Record the module into the list of -Xpatch entries only if
+    // Record the module into the list of --patch-module entries only if
     // valid ClassPathEntrys have been created
     if (module_cpl->module_first_entry() != NULL) {
-      _xpatch_entries->push(module_cpl);
+      _patch_mod_entries->push(module_cpl);
     }
   }
 }
@@ -1020,9 +1020,9 @@
   ClassPathEntry* e;
   tty->print("[bootclasspath= ");
 
-  // Print -Xpatch module/path specifications first
-  if (_xpatch_entries != NULL) {
-    print_module_entry_table(_xpatch_entries);
+  // Print --patch-module module/path specifications first
+  if (_patch_mod_entries != NULL) {
+    print_module_entry_table(_patch_mod_entries);
   }
 
   // [jimage | exploded modules build]
@@ -1341,7 +1341,7 @@
   return file_name;
 }
 
-// Search either the xpatch or exploded build entries for class
+// Search either the patch-module or exploded build entries for class
 ClassFileStream* ClassLoader::search_module_entries(const GrowableArray<ModuleClassPathList*>* const module_list,
                                                     const char* const class_name, const char* const file_name, TRAPS) {
   ClassFileStream* stream = NULL;
@@ -1366,7 +1366,7 @@
     int num_of_entries = module_list->length();
     const Symbol* class_module_name = mod_entry->name();
 
-    // Loop through all the modules in either the xpatch or exploded entries looking for module
+    // Loop through all the modules in either the patch-module or exploded entries looking for module
     for (int i = 0; i < num_of_entries; i++) {
       ModuleClassPathList* module_cpl = module_list->at(i);
       Symbol* module_cpl_name = module_cpl->module_name();
@@ -1378,7 +1378,7 @@
         while (e != NULL) {
           stream = e->open_stream(file_name, CHECK_NULL);
           // No context.check is required since CDS is not supported
-          // for an exploded modules build or if -Xpatch is specified.
+          // for an exploded modules build or if --patch-module is specified.
           if (NULL != stream) {
             return stream;
           }
@@ -1420,32 +1420,32 @@
 
   // If DumpSharedSpaces is true boot loader visibility boundaries are set to:
   //   - [jimage] + [_first_append_entry to _last_append_entry] (all path entries).
-  // No -Xpatch entries or exploded module builds are included since CDS
-  // is not supported if -Xpatch or exploded module builds are used.
+  // No --patch-module entries or exploded module builds are included since CDS
+  // is not supported if --patch-module or exploded module builds are used.
   //
   // If search_append_only is true, boot loader visibility boundaries are
   // set to be _first_append_entry to the end. This includes:
   //   [-Xbootclasspath/a]; [jvmti appended entries]
   //
   // If both DumpSharedSpaces and search_append_only are false, boot loader
-  // visibility boundaries are set to be the -Xpatch entries plus the base piece.
+  // visibility boundaries are set to be the --patch-module entries plus the base piece.
   // This would include:
-  //   [-Xpatch:<module>=<file>(<pathsep><file>)*]; [jimage | exploded module build]
+  //   [--patch-module=<module>=<file>(<pathsep><file>)*]; [jimage | exploded module build]
   //
   // DumpSharedSpaces and search_append_only are mutually exclusive and cannot
   // be true at the same time.
   assert(!(DumpSharedSpaces && search_append_only), "DumpSharedSpaces and search_append_only are both true");
 
-  // Load Attempt #1: -Xpatch
-  // Determine the class' defining module.  If it appears in the _xpatch_entries,
+  // Load Attempt #1: --patch-module
+  // Determine the class' defining module.  If it appears in the _patch_mod_entries,
   // attempt to load the class from those locations specific to the module.
-  // Specifications to -Xpatch can contain a partial number of classes
+  // Specifications to --patch-module can contain a partial number of classes
   // that are part of the overall module definition.  So if a particular class is not
   // found within its module specification, the search should continue to Load Attempt #2.
-  // Note: The -Xpatch entries are never searched if the boot loader's
+  // Note: The --patch-module entries are never searched if the boot loader's
   //       visibility boundary is limited to only searching the append entries.
-  if (_xpatch_entries != NULL && !search_append_only && !DumpSharedSpaces) {
-    stream = search_module_entries(_xpatch_entries, class_name, file_name, CHECK_NULL);
+  if (_patch_mod_entries != NULL && !search_append_only && !DumpSharedSpaces) {
+    stream = search_module_entries(_patch_mod_entries, class_name, file_name, CHECK_NULL);
   }
 
   // Load Attempt #2: [jimage | exploded build]
@@ -1650,11 +1650,11 @@
   // Create the moduleEntry for java.base
   create_javabase();
 
-  // Setup the list of module/path pairs for -Xpatch processing
+  // Setup the list of module/path pairs for --patch-module processing
   // This must be done after the SymbolTable is created in order
   // to use fast_compare on module names instead of a string compare.
-  if (Arguments::get_xpatchprefix() != NULL) {
-    setup_xpatch_entries();
+  if (Arguments::get_patch_mod_prefix() != NULL) {
+    setup_patch_mod_entries();
   }
 
   // Setup the initial java.base/path pair for the exploded build entries.
--- a/hotspot/src/share/vm/classfile/classLoader.hpp	Mon Aug 15 08:28:26 2016 +0200
+++ b/hotspot/src/share/vm/classfile/classLoader.hpp	Wed Jul 05 22:05:22 2017 +0200
@@ -150,7 +150,7 @@
 
 // ModuleClassPathList contains a linked list of ClassPathEntry's
 // that have been specified for a specific module.  Currently,
-// the only way to specify a module/path pair is via the -Xpatch
+// the only way to specify a module/path pair is via the --patch-module
 // command line option.
 class ModuleClassPathList : public CHeapObj<mtClass> {
 private:
@@ -213,8 +213,8 @@
   static PerfCounter* _load_instance_class_failCounter;
 
   // The boot class path consists of 3 ordered pieces:
-  //  1. the module/path pairs specified to -Xpatch
-  //    -Xpatch:<module>=<file>(<pathsep><file>)*
+  //  1. the module/path pairs specified to --patch-module
+  //    --patch-module=<module>=<file>(<pathsep><file>)*
   //  2. the base piece
   //    [jimage | build with exploded modules]
   //  3. boot loader append path
@@ -223,8 +223,8 @@
   // The boot loader must obey this order when attempting
   // to load a class.
 
-  // 1. Contains the module/path pairs specified to -Xpatch
-  static GrowableArray<ModuleClassPathList*>* _xpatch_entries;
+  // 1. Contains the module/path pairs specified to --patch-module
+  static GrowableArray<ModuleClassPathList*>* _patch_mod_entries;
 
   // 2. the base piece
   //    Contains the ClassPathEntry of the modular java runtime image.
@@ -256,11 +256,11 @@
 
   // Initialization:
   //   - setup the boot loader's system class path
-  //   - setup the boot loader's xpatch entries, if present
+  //   - setup the boot loader's patch mod entries, if present
   //   - create the ModuleEntry for java.base
   static void setup_bootstrap_search_path();
   static void setup_search_path(const char *class_path, bool setting_bootstrap);
-  static void setup_xpatch_entries();
+  static void setup_patch_mod_entries();
   static void create_javabase();
 
   static void load_zip_library();
@@ -363,7 +363,7 @@
   // Add a module's exploded directory to the boot loader's exploded module build list
   static void add_to_exploded_build_list(Symbol* module_name, TRAPS);
 
-  // Attempt load of individual class from either the xpatch or exploded modules build lists
+  // Attempt load of individual class from either the patched or exploded modules build lists
   static ClassFileStream* search_module_entries(const GrowableArray<ModuleClassPathList*>* const module_list,
                                                 const char* const class_name,
                                                 const char* const file_name, TRAPS);
--- a/hotspot/src/share/vm/memory/filemap.cpp	Mon Aug 15 08:28:26 2016 +0200
+++ b/hotspot/src/share/vm/memory/filemap.cpp	Wed Jul 05 22:05:22 2017 +0200
@@ -911,8 +911,8 @@
     return false;
   }
 
-  if (Arguments::get_xpatchprefix() != NULL) {
-    FileMapInfo::fail_continue("The shared archive file cannot be used with -Xpatch.");
+  if (Arguments::get_patch_mod_prefix() != NULL) {
+    FileMapInfo::fail_continue("The shared archive file cannot be used with --patch-module.");
     return false;
   }
 
--- a/hotspot/src/share/vm/prims/jvmtiEnv.cpp	Mon Aug 15 08:28:26 2016 +0200
+++ b/hotspot/src/share/vm/prims/jvmtiEnv.cpp	Wed Jul 05 22:05:22 2017 +0200
@@ -24,6 +24,8 @@
 
 #include "precompiled.hpp"
 #include "classfile/classLoaderExt.hpp"
+#include "classfile/javaClasses.inline.hpp"
+#include "classfile/stringTable.hpp"
 #include "classfile/modules.hpp"
 #include "classfile/systemDictionary.hpp"
 #include "classfile/vmSymbols.hpp"
@@ -224,6 +226,7 @@
   return JVMTI_ERROR_NONE;
 } /* end GetNamedModule */
 
+
   //
   // Class functions
   //
@@ -3465,28 +3468,35 @@
 JvmtiEnv::GetSystemProperties(jint* count_ptr, char*** property_ptr) {
   jvmtiError err = JVMTI_ERROR_NONE;
 
-  *count_ptr = Arguments::PropertyList_count(Arguments::system_properties());
-
+  // Get the number of readable properties.
+  *count_ptr = Arguments::PropertyList_readable_count(Arguments::system_properties());
+
+  // Allocate memory to hold the exact number of readable properties.
   err = allocate(*count_ptr * sizeof(char *), (unsigned char **)property_ptr);
   if (err != JVMTI_ERROR_NONE) {
     return err;
   }
-  int i = 0 ;
-  for (SystemProperty* p = Arguments::system_properties(); p != NULL && i < *count_ptr; p = p->next(), i++) {
-    const char *key = p->key();
-    char **tmp_value = *property_ptr+i;
-    err = allocate((strlen(key)+1) * sizeof(char), (unsigned char**)tmp_value);
-    if (err == JVMTI_ERROR_NONE) {
-      strcpy(*tmp_value, key);
-    } else {
-      // clean up previously allocated memory.
-      for (int j=0; j<i; j++) {
-        Deallocate((unsigned char*)*property_ptr+j);
+  int readable_count = 0;
+  // Loop through the system properties until all the readable properties are found.
+  for (SystemProperty* p = Arguments::system_properties(); p != NULL && readable_count < *count_ptr; p = p->next()) {
+    if (p->is_readable()) {
+      const char *key = p->key();
+      char **tmp_value = *property_ptr+readable_count;
+      readable_count++;
+      err = allocate((strlen(key)+1) * sizeof(char), (unsigned char**)tmp_value);
+      if (err == JVMTI_ERROR_NONE) {
+        strcpy(*tmp_value, key);
+      } else {
+        // clean up previously allocated memory.
+        for (int j=0; j<readable_count; j++) {
+          Deallocate((unsigned char*)*property_ptr+j);
+        }
+        Deallocate((unsigned char*)property_ptr);
+        break;
       }
-      Deallocate((unsigned char*)property_ptr);
-      break;
     }
   }
+  assert(err != JVMTI_ERROR_NONE || readable_count == *count_ptr, "Bad readable property count");
   return err;
 } /* end GetSystemProperties */
 
@@ -3498,7 +3508,8 @@
   jvmtiError err = JVMTI_ERROR_NONE;
   const char *value;
 
-  value = Arguments::PropertyList_get_value(Arguments::system_properties(), property);
+  // Return JVMTI_ERROR_NOT_AVAILABLE if property is not readable or doesn't exist.
+  value = Arguments::PropertyList_get_readable_value(Arguments::system_properties(), property);
   if (value == NULL) {
     err =  JVMTI_ERROR_NOT_AVAILABLE;
   } else {
--- a/hotspot/src/share/vm/runtime/arguments.cpp	Mon Aug 15 08:28:26 2016 +0200
+++ b/hotspot/src/share/vm/runtime/arguments.cpp	Wed Jul 05 22:05:22 2017 +0200
@@ -110,7 +110,7 @@
 SystemProperty *Arguments::_java_class_path = NULL;
 SystemProperty *Arguments::_jdk_boot_class_path_append = NULL;
 
-GrowableArray<ModuleXPatchPath*> *Arguments::_xpatchprefix = NULL;
+GrowableArray<ModulePatchPath*> *Arguments::_patch_mod_prefix = NULL;
 PathString *Arguments::_system_boot_class_path = NULL;
 bool Arguments::_has_jimage = false;
 
@@ -161,6 +161,30 @@
   }
 }
 
+bool needs_module_property_warning = false;
+
+#define MODULE_PROPERTY_PREFIX "jdk.module"
+#define MODULE_PROPERTY_PREFIX_LEN 10
+#define MODULE_MAIN_PROPERTY "jdk.module.main"
+#define MODULE_MAIN_PROPERTY_LEN 15
+
+// Return TRUE if option matches property, or property=, or property..
+static bool matches_property_prefix(const char* option, const char* property, size_t len) {
+  return (strncmp(option, property, len) == 0) &&
+          (option[len] == '=' || option[len] == '.' || option[len] == '\0');
+}
+
+// Return true if the property is either "jdk.module" or starts with "jdk.module.",
+// but does not start with "jdk.module.main".
+// Return false if jdk.module.main because jdk.module.main and jdk.module.main.class
+// are valid non-internal system properties.
+// "property" should be passed without the leading "-D".
+bool Arguments::is_internal_module_property(const char* property) {
+  assert((strncmp(property, "-D", 2) != 0), "Unexpected leading -D");
+  return (matches_property_prefix(property, MODULE_PROPERTY_PREFIX, MODULE_PROPERTY_PREFIX_LEN) &&
+          !matches_property_prefix(property, MODULE_MAIN_PROPERTY, MODULE_MAIN_PROPERTY_LEN));
+}
+
 // Process java launcher properties.
 void Arguments::process_sun_java_launcher_properties(JavaVMInitArgs* args) {
   // See if sun.java.launcher, sun.java.launcher.is_altjvm or
@@ -197,7 +221,7 @@
   _system_boot_class_path = new PathString(NULL);
 
   PropertyList_add(&_system_properties, new SystemProperty("java.vm.specification.name",
-                                                                 "Java Virtual Machine Specification",  false));
+                                                           "Java Virtual Machine Specification",  false));
   PropertyList_add(&_system_properties, new SystemProperty("java.vm.version", VM_Version::vm_release(),  false));
   PropertyList_add(&_system_properties, new SystemProperty("java.vm.name", VM_Version::vm_name(),  false));
   PropertyList_add(&_system_properties, new SystemProperty("java.vm.info", VM_Version::vm_info_string(),  true));
@@ -1198,7 +1222,7 @@
   return PropertyList_get_value(system_properties(), key);
 }
 
-bool Arguments::add_property(const char* prop) {
+bool Arguments::add_property(const char* prop, PropertyWriteable writeable, PropertyInternal internal) {
   const char* eq = strchr(prop, '=');
   const char* key;
   const char* value = "";
@@ -1228,7 +1252,9 @@
     // private and are processed in process_sun_java_launcher_properties();
     // the sun.java.launcher property is passed on to the java application
   } else if (strcmp(key, "sun.boot.library.path") == 0) {
-    PropertyList_unique_add(&_system_properties, key, value, true);
+    // append is true, writable is true, internal is false
+    PropertyList_unique_add(&_system_properties, key, value, AppendProperty,
+                            WriteableProperty, ExternalProperty);
   } else {
     if (strcmp(key, "sun.java.command") == 0) {
       char *old_java_command = _java_command;
@@ -1248,7 +1274,7 @@
     }
 
     // Create new property and add at the end of the list
-    PropertyList_unique_add(&_system_properties, key, value);
+    PropertyList_unique_add(&_system_properties, key, value, AddProperty, writeable, internal);
   }
 
   if (key != prop) {
@@ -1260,9 +1286,9 @@
   return true;
 }
 
-// sets or adds a module name to the jdk.launcher.addmods property
+// sets or adds a module name to the jdk.module.addmods property
 bool Arguments::append_to_addmods_property(const char* module_name) {
-  const char* key = "jdk.launcher.addmods";
+  const char* key = "jdk.module.addmods";
   const char* old_value = Arguments::get_property(key);
   size_t buf_len = strlen(key) + strlen(module_name) + 2;
   if (old_value != NULL) {
@@ -1277,7 +1303,7 @@
   } else {
     jio_snprintf(new_value, buf_len, "%s=%s,%s", key, old_value, module_name);
   }
-  bool added = add_property(new_value);
+  bool added = add_property(new_value, UnwriteableProperty, InternalProperty);
   FreeHeap(new_value);
   return added;
 }
@@ -1287,14 +1313,14 @@
   assert(DumpSharedSpaces, "this function is only used with -Xshare:dump");
   const char* unsupported_properties[5] = { "jdk.module.main",
                                            "jdk.module.path",
-                                           "jdk.upgrade.module.path",
-                                           "jdk.launcher.addmods",
-                                           "jdk.launcher.limitmods" };
+                                           "jdk.module.upgrade.path",
+                                           "jdk.module.addmods",
+                                           "jdk.module.limitmods" };
   const char* unsupported_options[5] = { "-m",
-                                        "-modulepath",
-                                        "-upgrademodulepath",
-                                        "-addmods",
-                                        "-limitmods" };
+                                        "--module-path",
+                                        "--upgrade-module-path",
+                                        "--add-modules",
+                                        "--limit-modules" };
   SystemProperty* sp = system_properties();
   while (sp != NULL) {
     for (int i = 0; i < 5; i++) {
@@ -1326,7 +1352,7 @@
   // Ensure Agent_OnLoad has the correct initial values.
   // This may not be the final mode; mode may change later in onload phase.
   PropertyList_unique_add(&_system_properties, "java.vm.info",
-                          VM_Version::vm_info_string(), false);
+                          VM_Version::vm_info_string(), AddProperty, UnwriteableProperty, ExternalProperty);
 
   UseInterpreter             = true;
   UseCompiler                = true;
@@ -2516,6 +2542,41 @@
   return false;
 }
 
+unsigned int addreads_count = 0;
+unsigned int addexports_count = 0;
+unsigned int patch_mod_count = 0;
+const char* add_modules_value = NULL;
+
+bool Arguments::create_property(const char* prop_name, const char* prop_value, PropertyInternal internal) {
+  size_t prop_len = strlen(prop_name) + strlen(prop_value) + 2;
+  char* property = AllocateHeap(prop_len, mtArguments);
+  int ret = jio_snprintf(property, prop_len, "%s=%s", prop_name, prop_value);
+  if (ret < 0 || ret >= (int)prop_len) {
+    FreeHeap(property);
+    return false;
+  }
+  bool added = add_property(property, UnwriteableProperty, internal);
+  FreeHeap(property);
+  return added;
+}
+
+bool Arguments::create_numbered_property(const char* prop_base_name, const char* prop_value, unsigned int count) {
+  // Make sure count is < 1,000. Otherwise, memory allocation will be too small.
+  if (count < 1000) {
+    size_t prop_len = strlen(prop_base_name) + strlen(prop_value) + 5;
+    char* property = AllocateHeap(prop_len, mtArguments);
+    int ret = jio_snprintf(property, prop_len, "%s.%d=%s", prop_base_name, count, prop_value);
+    if (ret < 0 || ret >= (int)prop_len) {
+      FreeHeap(property);
+      return false;
+    }
+    bool added = add_property(property, UnwriteableProperty, InternalProperty);
+    FreeHeap(property);
+    return added;
+  }
+  return false;
+}
+
 Arguments::ArgsRange Arguments::parse_memory_size(const char* s,
                                                   julong* long_arg,
                                                   julong min_size) {
@@ -2528,7 +2589,7 @@
 jint Arguments::parse_vm_init_args(const JavaVMInitArgs *java_tool_options_args,
                                    const JavaVMInitArgs *java_options_args,
                                    const JavaVMInitArgs *cmd_line_args) {
-  bool xpatch_javabase = false;
+  bool patch_mod_javabase = false;
 
   // Save default settings for some mode flags
   Arguments::_AlwaysCompileLoopMethods = AlwaysCompileLoopMethods;
@@ -2545,20 +2606,20 @@
 
   // Parse args structure generated from JAVA_TOOL_OPTIONS environment
   // variable (if present).
-  jint result = parse_each_vm_init_arg(java_tool_options_args, &xpatch_javabase, Flag::ENVIRON_VAR);
+  jint result = parse_each_vm_init_arg(java_tool_options_args, &patch_mod_javabase, Flag::ENVIRON_VAR);
   if (result != JNI_OK) {
     return result;
   }
 
   // Parse args structure generated from the command line flags.
-  result = parse_each_vm_init_arg(cmd_line_args, &xpatch_javabase, Flag::COMMAND_LINE);
+  result = parse_each_vm_init_arg(cmd_line_args, &patch_mod_javabase, Flag::COMMAND_LINE);
   if (result != JNI_OK) {
     return result;
   }
 
   // Parse args structure generated from the _JAVA_OPTIONS environment
   // variable (if present) (mimics classic VM)
-  result = parse_each_vm_init_arg(java_options_args, &xpatch_javabase, Flag::ENVIRON_VAR);
+  result = parse_each_vm_init_arg(java_options_args, &patch_mod_javabase, Flag::ENVIRON_VAR);
   if (result != JNI_OK) {
     return result;
   }
@@ -2617,7 +2678,35 @@
   return false;
 }
 
-jint Arguments::parse_each_vm_init_arg(const JavaVMInitArgs* args, bool* xpatch_javabase, Flag::Flags origin) {
+int Arguments::process_patch_mod_option(const char* patch_mod_tail, bool* patch_mod_javabase) {
+  // --patch-module=<module>=<file>(<pathsep><file>)*
+  assert(patch_mod_tail != NULL, "Unexpected NULL patch-module value");
+  // Find the equal sign between the module name and the path specification
+  const char* module_equal = strchr(patch_mod_tail, '=');
+  if (module_equal == NULL) {
+    jio_fprintf(defaultStream::output_stream(), "Missing '=' in --patch-module specification\n");
+    return JNI_ERR;
+  } else {
+    // Pick out the module name
+    size_t module_len = module_equal - patch_mod_tail;
+    char* module_name = NEW_C_HEAP_ARRAY_RETURN_NULL(char, module_len+1, mtArguments);
+    if (module_name != NULL) {
+      memcpy(module_name, patch_mod_tail, module_len);
+      *(module_name + module_len) = '\0';
+      // The path piece begins one past the module_equal sign
+      add_patch_mod_prefix(module_name, module_equal + 1, patch_mod_javabase);
+      FREE_C_HEAP_ARRAY(char, module_name);
+      if (!create_numbered_property("jdk.module.patch", patch_mod_tail, patch_mod_count++)) {
+        return JNI_ENOMEM;
+      }
+    } else {
+      return JNI_ENOMEM;
+    }
+  }
+  return JNI_OK;
+}
+
+jint Arguments::parse_each_vm_init_arg(const JavaVMInitArgs* args, bool* patch_mod_javabase, Flag::Flags origin) {
   // For match_option to return remaining or value part of option string
   const char* tail;
 
@@ -2701,6 +2790,34 @@
 #endif // !INCLUDE_JVMTI
         add_init_library(name, options);
       }
+    } else if (match_option(option, "--add-reads=", &tail)) {
+      if (!create_numbered_property("jdk.module.addreads", tail, addreads_count++)) {
+        return JNI_ENOMEM;
+      }
+    } else if (match_option(option, "--add-exports=", &tail)) {
+      if (!create_numbered_property("jdk.module.addexports", tail, addexports_count++)) {
+        return JNI_ENOMEM;
+      }
+    } else if (match_option(option, "--add-modules=", &tail)) {
+      add_modules_value = tail;
+    } else if (match_option(option, "--limit-modules=", &tail)) {
+      if (!create_property("jdk.module.limitmods", tail, InternalProperty)) {
+        return JNI_ENOMEM;
+      }
+    } else if (match_option(option, "--module-path=", &tail)) {
+      if (!create_property("jdk.module.path", tail, ExternalProperty)) {
+        return JNI_ENOMEM;
+      }
+    } else if (match_option(option, "--upgrade-module-path=", &tail)) {
+      if (!create_property("jdk.module.upgrade.path", tail, ExternalProperty)) {
+        return JNI_ENOMEM;
+      }
+    } else if (match_option(option, "--patch-module=", &tail)) {
+      // --patch-module=<module>=<file>(<pathsep><file>)*
+      int res = process_patch_mod_option(tail, patch_mod_javabase);
+      if (res != JNI_OK) {
+        return res;
+      }
     // -agentlib and -agentpath
     } else if (match_option(option, "-agentlib:", &tail) ||
           (is_absolute_path = match_option(option, "-agentpath:", &tail))) {
@@ -2992,6 +3109,13 @@
           "-Djava.ext.dirs=%s is not supported.  Use -classpath instead.\n", value);
         return JNI_EINVAL;
       }
+      // Check for module related properties.  They must be set using the modules
+      // options. For example: use "--add-modules=java.sql", not
+      // "-Djdk.module.addmods=java.sql"
+      if (is_internal_module_property(option->optionString + 2)) {
+        needs_module_property_warning = true;
+        continue;
+      }
 
       if (!add_property(tail)) {
         return JNI_ENOMEM;
@@ -3012,33 +3136,6 @@
         return JNI_ERR;
 #endif
       }
-      if (match_option(option, "-Djdk.launcher.patch.", &tail)) {
-        // -Djdk.launcher.patch.#=<module>=<file>(<pathsep><file>)*
-        // The number, #, specified will be increasing with each -Xpatch
-        // specified on the command line.
-        // Pick up module name, following the -D property's equal sign.
-        const char* property_equal = strchr(tail, '=');
-        if (property_equal == NULL) {
-          jio_fprintf(defaultStream::output_stream(), "Missing '=' in -Xpatch specification\n");
-          return JNI_ERR;
-        } else {
-          // Find the equal sign between the module name and the path specification
-          const char* module_equal = strchr(property_equal + 1, '=');
-          if (module_equal == NULL) {
-            jio_fprintf(defaultStream::output_stream(), "Bad value for -Xpatch, no module name specified\n");
-            return JNI_ERR;
-          } else {
-            // Pick out the module name, in between the two equal signs
-            size_t module_len = module_equal - property_equal - 1;
-            char* module_name = NEW_C_HEAP_ARRAY(char, module_len+1, mtArguments);
-            memcpy(module_name, property_equal + 1, module_len);
-            *(module_name + module_len) = '\0';
-            // The path piece begins one past the module_equal sign
-            Arguments::add_xpatchprefix(module_name, module_equal + 1, xpatch_javabase);
-            FREE_C_HEAP_ARRAY(char, module_name);
-          }
-        }
-      }
     // -Xint
     } else if (match_option(option, "-Xint")) {
           set_mode_flags(_int);
@@ -3298,25 +3395,25 @@
   return JNI_OK;
 }
 
-void Arguments::add_xpatchprefix(const char* module_name, const char* path, bool* xpatch_javabase) {
-  // For java.base check for duplicate -Xpatch options being specified on the command line.
+void Arguments::add_patch_mod_prefix(const char* module_name, const char* path, bool* patch_mod_javabase) {
+  // For java.base check for duplicate --patch-module options being specified on the command line.
   // This check is only required for java.base, all other duplicate module specifications
   // will be checked during module system initialization.  The module system initialization
   // will throw an ExceptionInInitializerError if this situation occurs.
   if (strcmp(module_name, "java.base") == 0) {
-    if (*xpatch_javabase) {
-      vm_exit_during_initialization("Cannot specify java.base more than once to -Xpatch");
+    if (*patch_mod_javabase) {
+      vm_exit_during_initialization("Cannot specify java.base more than once to --patch-module");
     } else {
-      *xpatch_javabase = true;
+      *patch_mod_javabase = true;
     }
   }
 
-  // Create GrowableArray lazily, only if -Xpatch has been specified
-  if (_xpatchprefix == NULL) {
-    _xpatchprefix = new (ResourceObj::C_HEAP, mtArguments) GrowableArray<ModuleXPatchPath*>(10, true);
-  }
-
-  _xpatchprefix->push(new ModuleXPatchPath(module_name, path));
+  // Create GrowableArray lazily, only if --patch-module has been specified
+  if (_patch_mod_prefix == NULL) {
+    _patch_mod_prefix = new (ResourceObj::C_HEAP, mtArguments) GrowableArray<ModulePatchPath*>(10, true);
+  }
+
+  _patch_mod_prefix->push(new ModulePatchPath(module_name, path));
 }
 
 // Remove all empty paths from the app classpath (if IgnoreEmptyClassPaths is enabled)
@@ -3441,6 +3538,15 @@
     return JNI_ERR;
   }
 
+  // Append the value of the last --add-modules option specified on the command line.
+  // This needs to be done here, to prevent overwriting possible values written
+  // to the jdk.module.addmods property by -javaagent and other options.
+  if (add_modules_value != NULL) {
+    if (!append_to_addmods_property(add_modules_value)) {
+      return JNI_ENOMEM;
+    }
+  }
+
   // This must be done after all arguments have been processed.
   // java_compiler() true means set to "NONE" or empty.
   if (java_compiler() && !xdebug_mode()) {
@@ -3795,9 +3901,9 @@
 
 void Arguments::set_shared_spaces_flags() {
   if (DumpSharedSpaces) {
-    if (Arguments::get_xpatchprefix() != NULL) {
+    if (Arguments::get_patch_mod_prefix() != NULL) {
       vm_exit_during_initialization(
-        "Cannot use the following option when dumping the shared archive", "-Xpatch");
+        "Cannot use the following option when dumping the shared archive: --patch-module");
     }
 
     if (RequireSharedSpaces) {
@@ -4180,6 +4286,11 @@
             hotspotrc, hotspotrc);
   }
 
+  if (needs_module_property_warning) {
+    warning("Ignoring system property options whose names start with '-Djdk.module'."
+            "  They are reserved for internal use.");
+  }
+
 #if defined(_ALLBSD_SOURCE) || defined(AIX)  // UseLargePages is not yet supported on BSD and AIX.
   UNSUPPORTED_OPTION(UseLargePages);
 #endif
@@ -4404,6 +4515,18 @@
   return count;
 }
 
+// Return the number of readable properties.
+int Arguments::PropertyList_readable_count(SystemProperty* pl) {
+  int count = 0;
+  while(pl != NULL) {
+    if (pl->is_readable()) {
+      count++;
+    }
+    pl = pl->next();
+  }
+  return count;
+}
+
 const char* Arguments::PropertyList_get_value(SystemProperty *pl, const char* key) {
   assert(key != NULL, "just checking");
   SystemProperty* prop;
@@ -4413,6 +4536,27 @@
   return NULL;
 }
 
+// Return the value of the requested property provided that it is a readable property.
+const char* Arguments::PropertyList_get_readable_value(SystemProperty *pl, const char* key) {
+  assert(key != NULL, "just checking");
+  SystemProperty* prop;
+  // Return the property value if the keys match and the property is not internal or
+  // it's the special internal property "jdk.boot.class.path.append".
+  for (prop = pl; prop != NULL; prop = prop->next()) {
+    if (strcmp(key, prop->key()) == 0) {
+      if (!prop->internal()) {
+        return prop->value();
+      } else if (strcmp(key, "jdk.boot.class.path.append") == 0) {
+        return prop->value();
+      } else {
+        // Property is internal and not jdk.boot.class.path.append so return NULL.
+        return NULL;
+      }
+    }
+  }
+  return NULL;
+}
+
 const char* Arguments::PropertyList_get_key_at(SystemProperty *pl, int index) {
   int count = 0;
   const char* ret_val = NULL;
@@ -4457,11 +4601,12 @@
   }
 }
 
-void Arguments::PropertyList_add(SystemProperty** plist, const char* k, const char* v) {
+void Arguments::PropertyList_add(SystemProperty** plist, const char* k, const char* v,
+                                 bool writeable, bool internal) {
   if (plist == NULL)
     return;
 
-  SystemProperty* new_p = new SystemProperty(k, v, true);
+  SystemProperty* new_p = new SystemProperty(k, v, writeable, internal);
   PropertyList_add(plist, new_p);
 }
 
@@ -4470,7 +4615,9 @@
 }
 
 // This add maintains unique property key in the list.
-void Arguments::PropertyList_unique_add(SystemProperty** plist, const char* k, const char* v, jboolean append) {
+void Arguments::PropertyList_unique_add(SystemProperty** plist, const char* k, const char* v,
+                                        PropertyAppendable append, PropertyWriteable writeable,
+                                        PropertyInternal internal) {
   if (plist == NULL)
     return;
 
@@ -4478,16 +4625,16 @@
   SystemProperty* prop;
   for (prop = *plist; prop != NULL; prop = prop->next()) {
     if (strcmp(k, prop->key()) == 0) {
-      if (append) {
+      if (append == AppendProperty) {
         prop->append_value(v);
       } else {
-        prop->set_writeable_value(v);
+        prop->set_value(v);
       }
       return;
     }
   }
 
-  PropertyList_add(plist, k, v);
+  PropertyList_add(plist, k, v, writeable == WriteableProperty, internal == InternalProperty);
 }
 
 // Copies src into buf, replacing "%%" with "%" and "%p" with pid
--- a/hotspot/src/share/vm/runtime/arguments.hpp	Mon Aug 15 08:28:26 2016 +0200
+++ b/hotspot/src/share/vm/runtime/arguments.hpp	Wed Jul 05 22:05:22 2017 +0200
@@ -43,7 +43,7 @@
 
 // PathString is used as:
 //  - the underlying value for a SystemProperty
-//  - the path portion of an -Xpatch module/path pair
+//  - the path portion of an --patch-module module/path pair
 //  - the string that represents the system boot class path, Arguments::_system_boot_class_path.
 class PathString : public CHeapObj<mtArguments> {
  protected:
@@ -107,13 +107,13 @@
   }
 };
 
-// ModuleXPatchPath records the module/path pair as specified to -Xpatch.
-class ModuleXPatchPath : public CHeapObj<mtInternal> {
+// ModulePatchPath records the module/path pair as specified to --patch-module.
+class ModulePatchPath : public CHeapObj<mtInternal> {
 private:
   char* _module_name;
   PathString* _path;
 public:
-  ModuleXPatchPath(const char* module_name, const char* path) {
+  ModulePatchPath(const char* module_name, const char* path) {
     assert(module_name != NULL && path != NULL, "Invalid module name or path value");
     size_t len = strlen(module_name) + 1;
     _module_name = AllocateHeap(len, mtInternal);
@@ -121,7 +121,7 @@
     _path =  new PathString(path);
   }
 
-  ~ModuleXPatchPath() {
+  ~ModulePatchPath() {
     if (_module_name != NULL) {
       FreeHeap(_module_name);
       _module_name = NULL;
@@ -158,6 +158,10 @@
   SystemProperty* next() const        { return _next; }
   void set_next(SystemProperty* next) { _next = next; }
 
+  bool is_readable() const {
+    return !_internal || strcmp(_key, "jdk.boot.class.path.append") == 0;
+  }
+
   // A system property should only have its value set
   // via an external interface if it is a writeable property.
   // The internal, non-writeable property jdk.boot.class.path.append
@@ -325,6 +329,21 @@
     arg_in_range   = 0
   };
 
+  enum PropertyAppendable {
+    AppendProperty,
+    AddProperty
+  };
+
+  enum PropertyWriteable {
+    WriteableProperty,
+    UnwriteableProperty
+  };
+
+  enum PropertyInternal {
+    InternalProperty,
+    ExternalProperty
+  };
+
  private:
 
   // a pointer to the flags file name if it is specified
@@ -348,18 +367,18 @@
   static SystemProperty *_java_class_path;
   static SystemProperty *_jdk_boot_class_path_append;
 
-  // -Xpatch:module=<file>(<pathsep><file>)*
+  // --patch-module=module=<file>(<pathsep><file>)*
   // Each element contains the associated module name, path
-  // string pair as specified to -Xpatch.
-  static GrowableArray<ModuleXPatchPath*>* _xpatchprefix;
+  // string pair as specified to --patch-module.
+  static GrowableArray<ModulePatchPath*>* _patch_mod_prefix;
 
   // The constructed value of the system class path after
   // argument processing and JVMTI OnLoad additions via
   // calls to AddToBootstrapClassLoaderSearch.  This is the
   // final form before ClassLoader::setup_bootstrap_search().
-  // Note: since -Xpatch is a module name/path pair, the system
-  // boot class path string no longer contains the "prefix" to
-  // the boot class path base piece as it did when
+  // Note: since --patch-module is a module name/path pair, the
+  // system boot class path string no longer contains the "prefix"
+  // to the boot class path base piece as it did when
   // -Xbootclasspath/p was supported.
   static PathString *_system_boot_class_path;
 
@@ -462,7 +481,13 @@
   static vfprintf_hook_t  _vfprintf_hook;
 
   // System properties
-  static bool add_property(const char* prop);
+  static bool add_property(const char* prop, PropertyWriteable writeable=WriteableProperty,
+                           PropertyInternal internal=ExternalProperty);
+
+  static bool create_property(const char* prop_name, const char* prop_value, PropertyInternal internal);
+  static bool create_numbered_property(const char* prop_base_name, const char* prop_value, unsigned int count);
+
+  static int process_patch_mod_option(const char* patch_mod_tail, bool* patch_mod_javabase);
 
   // Miscellaneous system property setter
   static bool append_to_addmods_property(const char* module_name);
@@ -500,7 +525,7 @@
   static jint parse_vm_init_args(const JavaVMInitArgs *java_tool_options_args,
                                  const JavaVMInitArgs *java_options_args,
                                  const JavaVMInitArgs *cmd_line_args);
-  static jint parse_each_vm_init_arg(const JavaVMInitArgs* args, bool* xpatch_javabase, Flag::Flags origin);
+  static jint parse_each_vm_init_arg(const JavaVMInitArgs* args, bool* patch_mod_javabase, Flag::Flags origin);
   static jint finalize_vm_init_args();
   static bool is_bad_option(const JavaVMOption* option, jboolean ignore, const char* option_type);
 
@@ -708,16 +733,20 @@
   // Property List manipulation
   static void PropertyList_add(SystemProperty *element);
   static void PropertyList_add(SystemProperty** plist, SystemProperty *element);
-  static void PropertyList_add(SystemProperty** plist, const char* k, const char* v);
-  static void PropertyList_unique_add(SystemProperty** plist, const char* k, const char* v) {
-    PropertyList_unique_add(plist, k, v, false);
-  }
-  static void PropertyList_unique_add(SystemProperty** plist, const char* k, const char* v, jboolean append);
+  static void PropertyList_add(SystemProperty** plist, const char* k, const char* v, bool writeable, bool internal);
+
+  static void PropertyList_unique_add(SystemProperty** plist, const char* k, const char* v,
+                                      PropertyAppendable append, PropertyWriteable writeable,
+                                      PropertyInternal internal);
   static const char* PropertyList_get_value(SystemProperty* plist, const char* key);
+  static const char* PropertyList_get_readable_value(SystemProperty* plist, const char* key);
   static int  PropertyList_count(SystemProperty* pl);
+  static int  PropertyList_readable_count(SystemProperty* pl);
   static const char* PropertyList_get_key_at(SystemProperty* pl,int index);
   static char* PropertyList_get_value_at(SystemProperty* pl,int index);
 
+  static bool is_internal_module_property(const char* option);
+
   // Miscellaneous System property value getter and setters.
   static void set_dll_dir(const char *value) { _sun_boot_library_path->set_value(value); }
   static void set_java_home(const char *value) { _java_home->set_value(value); }
@@ -725,7 +754,7 @@
   static void set_ext_dirs(char *value)     { _ext_dirs = os::strdup_check_oom(value); }
 
   // Set up the underlying pieces of the system boot class path
-  static void add_xpatchprefix(const char *module_name, const char *path, bool* xpatch_javabase);
+  static void add_patch_mod_prefix(const char *module_name, const char *path, bool* patch_mod_javabase);
   static void set_sysclasspath(const char *value, bool has_jimage) {
     // During start up, set by os::set_boot_path()
     assert(get_sysclasspath() == NULL, "System boot class path previously set");
@@ -737,7 +766,7 @@
     _jdk_boot_class_path_append->append_value(value);
   }
 
-  static GrowableArray<ModuleXPatchPath*>* get_xpatchprefix() { return _xpatchprefix; }
+  static GrowableArray<ModulePatchPath*>* get_patch_mod_prefix() { return _patch_mod_prefix; }
   static char* get_sysclasspath() { return _system_boot_class_path->value(); }
   static char* get_jdk_boot_class_path_append() { return _jdk_boot_class_path_append->value(); }
   static bool has_jimage() { return _has_jimage; }
--- a/hotspot/src/share/vm/utilities/ostream.cpp	Mon Aug 15 08:28:26 2016 +0200
+++ b/hotspot/src/share/vm/utilities/ostream.cpp	Wed Jul 05 22:05:22 2017 +0200
@@ -703,13 +703,15 @@
       // System properties don't generally contain newlines, so don't bother with unparsing.
       outputStream *text = xs->text();
       for (SystemProperty* p = Arguments::system_properties(); p != NULL; p = p->next()) {
-        // Print in two stages to avoid problems with long
-        // keys/values.
         assert(p->key() != NULL, "p->key() is NULL");
-        text->print_raw(p->key());
-        text->put('=');
-        assert(p->value() != NULL, "p->value() is NULL");
-        text->print_raw_cr(p->value());
+        if (p->is_readable()) {
+          // Print in two stages to avoid problems with long
+          // keys/values.
+          text->print_raw(p->key());
+          text->put('=');
+          assert(p->value() != NULL, "p->value() is NULL");
+          text->print_raw_cr(p->value());
+        }
       }
       xs->tail("properties");
     }
--- a/hotspot/test/TEST.ROOT	Mon Aug 15 08:28:26 2016 +0200
+++ b/hotspot/test/TEST.ROOT	Wed Jul 05 22:05:22 2017 +0200
@@ -46,12 +46,12 @@
     vm.gc.Parallel \
     vm.gc.ConcMarkSweep
 
-# Tests using jtreg 4.2 b02 features
-requiredVersion=4.2 b02
+# Tests using jtreg 4.2 b03 features
+requiredVersion=4.2 b03
 
 # Path to libraries in the topmost test directory. This is needed so @library
 # does not need ../../ notation to reach them
 external.lib.roots = ../../
 
-# Use new form of -Xpatch
-useNewXpatch=true
+# Use new module options
+useNewOptions=true
--- a/hotspot/test/compiler/unsafe/UnsafeGetConstantField.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/hotspot/test/compiler/unsafe/UnsafeGetConstantField.java	Wed Jul 05 22:05:22 2017 +0200
@@ -40,7 +40,7 @@
  *                                 -XX:CompileCommand=dontinline,compiler.unsafe.UnsafeGetConstantField::checkGetAddress
  *                                 -XX:CompileCommand=dontinline,*::test*
  *                                 -XX:+UseUnalignedAccesses
- *                                 -XaddReads:java.base=ALL-UNNAMED
+ *                                 --add-reads=java.base=ALL-UNNAMED
  *                                 compiler.unsafe.UnsafeGetConstantField
  *
  * @run main/bootclasspath/othervm -XX:+UnlockDiagnosticVMOptions
@@ -50,7 +50,7 @@
  *                                 -XX:CompileCommand=dontinline,*::test*
  *                                 -XX:CompileCommand=inline,*Unsafe::get*
  *                                 -XX:-UseUnalignedAccesses
- *                                 -XaddReads:java.base=ALL-UNNAMED
+ *                                 --add-reads=java.base=ALL-UNNAMED
  *                                 compiler.unsafe.UnsafeGetConstantField
  */
 
--- a/hotspot/test/gc/arguments/TestMaxMinHeapFreeRatioFlags.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/hotspot/test/gc/arguments/TestMaxMinHeapFreeRatioFlags.java	Wed Jul 05 22:05:22 2017 +0200
@@ -88,7 +88,7 @@
                 (useXmaxf ? "-Xmaxf" + maxRatio / 100.0 : "-XX:MaxHeapFreeRatio=" + maxRatio),
                 "-Xmx" + MAX_HEAP_SIZE,
                 "-Xms" + HEAP_SIZE,
-                "-XaddExports:java.base/jdk.internal.misc=ALL-UNNAMED",
+                "--add-exports=java.base/jdk.internal.misc=ALL-UNNAMED",
                 "-XX:NewSize=" + NEW_SIZE,
                 "-XX:MaxNewSize=" + MAX_NEW_SIZE,
                 "-XX:" + (shrinkHeapInSteps ? '+' : '-') + "ShrinkHeapInSteps",
@@ -120,7 +120,7 @@
         Collections.addAll(vmOptions,
                 (useXminf ? "-Xminf" + minRatio / 100.0 : "-XX:MinHeapFreeRatio=" + minRatio),
                 (useXmaxf ? "-Xmaxf" + maxRatio / 100.0 : "-XX:MaxHeapFreeRatio=" + maxRatio),
-                "-XaddExports:java.base/jdk.internal.misc=ALL-UNNAMED",
+                "--add-exports=java.base/jdk.internal.misc=ALL-UNNAMED",
                 "-version"
         );
         ProcessBuilder procBuilder = ProcessTools.createJavaProcessBuilder(vmOptions.toArray(new String[vmOptions.size()]));
--- a/hotspot/test/gc/arguments/TestSurvivorRatioFlag.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/hotspot/test/gc/arguments/TestSurvivorRatioFlag.java	Wed Jul 05 22:05:22 2017 +0200
@@ -74,7 +74,7 @@
 
         Collections.addAll(vmOptions,
                 "-Xbootclasspath/a:.",
-                "-XaddExports:java.base/jdk.internal.misc=ALL-UNNAMED",
+                "--add-exports=java.base/jdk.internal.misc=ALL-UNNAMED",
                 "-XX:+UnlockDiagnosticVMOptions",
                 "-XX:+WhiteBoxAPI",
                 "-XX:GCLockerEdenExpansionPercent=0",
--- a/hotspot/test/gc/arguments/TestTargetSurvivorRatioFlag.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/hotspot/test/gc/arguments/TestTargetSurvivorRatioFlag.java	Wed Jul 05 22:05:22 2017 +0200
@@ -132,7 +132,7 @@
         LinkedList<String> vmOptions = new LinkedList<>(options);
         Collections.addAll(vmOptions,
                 "-Xbootclasspath/a:.",
-                "-XaddExports:java.base/jdk.internal.misc=ALL-UNNAMED",
+                "--add-exports=java.base/jdk.internal.misc=ALL-UNNAMED",
                 "-XX:+UnlockDiagnosticVMOptions",
                 "-XX:+WhiteBoxAPI",
                 "-XX:+UseAdaptiveSizePolicy",
--- a/hotspot/test/gc/g1/TestShrinkAuxiliaryData.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/hotspot/test/gc/g1/TestShrinkAuxiliaryData.java	Wed Jul 05 22:05:22 2017 +0200
@@ -53,7 +53,7 @@
         "-Xlog:gc=debug",
         "-XX:+UnlockDiagnosticVMOptions",
         "-XX:+WhiteBoxAPI",
-        "-XaddExports:java.base/jdk.internal.misc=ALL-UNNAMED",
+        "--add-exports=java.base/jdk.internal.misc=ALL-UNNAMED",
         "-Xbootclasspath/a:.",
     };
 
--- a/hotspot/test/runtime/BadObjectClass/BootstrapRedefine.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/hotspot/test/runtime/BadObjectClass/BootstrapRedefine.java	Wed Jul 05 22:05:22 2017 +0200
@@ -48,7 +48,7 @@
                                         "-Xmodule:java.base"),
                                         "mods/java.base");
 
-        ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-Xpatch:java.base=mods/java.base", "-version");
+        ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("--patch-module=java.base=mods/java.base", "-version");
         new OutputAnalyzer(pb.start())
             .shouldContain("Incompatible definition of java.lang.Object")
             .shouldHaveExitValue(1);
--- a/hotspot/test/runtime/BootClassAppendProp/BootClassPathAppendProp.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/hotspot/test/runtime/BootClassAppendProp/BootClassPathAppendProp.java	Wed Jul 05 22:05:22 2017 +0200
@@ -27,7 +27,7 @@
  * @test
  * @build BootClassPathAppendProp
  * @run main/othervm -Xbootclasspath/a:/usr/lib -showversion -Xbootclasspath/a:/i/dont/exist BootClassPathAppendProp
- * @run main/othervm -Xpatch:/not/here -Xbootclasspath/a:/i/may/exist BootClassPathAppendProp
+ * @run main/othervm --patch-module=no_module=/not/here -Xbootclasspath/a:/i/may/exist BootClassPathAppendProp
  * @run main/othervm -Djdk.boot.class.path.append=newdir BootClassPathAppendProp
  * @run main/othervm BootClassPathAppendProp
  */
--- a/hotspot/test/runtime/ErrorHandling/CreateCoredumpOnCrash.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/hotspot/test/runtime/ErrorHandling/CreateCoredumpOnCrash.java	Wed Jul 05 22:05:22 2017 +0200
@@ -56,7 +56,7 @@
     public static OutputAnalyzer runTest(String option) throws Exception {
         return new OutputAnalyzer(
             ProcessTools.createJavaProcessBuilder(
-            "-Xmx64m", "-XX:-TransmitErrorReport", "-XaddExports:java.base/jdk.internal.misc=ALL-UNNAMED", option, Crasher.class.getName())
+            "-Xmx64m", "-XX:-TransmitErrorReport", "--add-exports=java.base/jdk.internal.misc=ALL-UNNAMED", option, Crasher.class.getName())
             .start());
     }
 }
--- a/hotspot/test/runtime/ErrorHandling/ProblematicFrameTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/hotspot/test/runtime/ErrorHandling/ProblematicFrameTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -48,7 +48,7 @@
 
     public static void main(String[] args) throws Exception {
         ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
-            "-Xmx64m", "-XX:-TransmitErrorReport", "-XaddExports:java.base/jdk.internal.misc=ALL-UNNAMED", "-XX:-CreateCoredumpOnCrash", Crasher.class.getName());
+            "-Xmx64m", "-XX:-TransmitErrorReport", "--add-exports=java.base/jdk.internal.misc=ALL-UNNAMED", "-XX:-CreateCoredumpOnCrash", Crasher.class.getName());
         OutputAnalyzer output = new OutputAnalyzer(pb.start());
         output.shouldNotContain("Exception in thread");
         output.shouldNotMatch("error occurred during error reporting \\(printing problematic frame\\)");
--- a/hotspot/test/runtime/SharedArchiveFile/BootAppendTests.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/hotspot/test/runtime/SharedArchiveFile/BootAppendTests.java	Wed Jul 05 22:05:22 2017 +0200
@@ -160,10 +160,10 @@
 
     // Test #3: If a class on -Xbootclasspath/a is from a package defined in boot modules,
     //          the class can be loaded from -Xbootclasspath/a when the module is excluded
-    //          using -limitmods. Verify the behavior is the same at runtime when CDS is
-    //          enabled.
+    //          using --limit-modules. Verify the behavior is the same at runtime when CDS
+    //          is enabled.
     //
-    //          The java.desktop module is excluded using -limitmods at runtime,
+    //          The java.desktop module is excluded using --limit-modules at runtime,
     //          javax.sound.sampled.MyClass is archived from -Xbootclasspath/a. It can be
     //          loaded from the archive at runtime.
     public static void testBootAppendExcludedModuleClass() throws Exception {
@@ -174,7 +174,7 @@
                 "-XX:+TraceClassLoading",
                 "-cp", appJar,
                 "-Xbootclasspath/a:" + bootAppendJar,
-                "-limitmods", "java.base",
+                "--limit-modules=java.base",
                 "-Xshare:" + mode,
                 APP_CLASS,
                 BOOT_APPEND_MODULE_CLASS_NAME);
@@ -191,8 +191,8 @@
     // Test #4: If a class on -Xbootclasspath/a has the same fully qualified
     //          name as a class defined in boot modules, the class is loaded
     //          from -Xbootclasspath/a when the boot module is excluded using
-    //          -limitmods. Verify the behavior is the same at runtime when CDS is
-    //          enabled.
+    //          --limit-modules. Verify the behavior is the same at runtime
+    //          when CDS is enabled.
     //
     //          The org.omg.CORBA.Context is a boot module class. The class
     //          on -Xbootclasspath/a that has the same fully-qualified name
@@ -206,7 +206,7 @@
                 "-XX:+TraceClassLoading",
                 "-cp", appJar,
                 "-Xbootclasspath/a:" + bootAppendJar,
-                "-limitmods", "java.base",
+                "--limit-modules=java.base",
                 "-Xshare:" + mode,
                 APP_CLASS,
                 BOOT_APPEND_DUPLICATE_MODULE_CLASS_NAME);
--- a/hotspot/test/runtime/SharedArchiveFile/SASymbolTableTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/hotspot/test/runtime/SharedArchiveFile/SASymbolTableTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -89,10 +89,11 @@
         long pid = p.getPid();
         System.out.println("Attaching agent " + pid);
         ProcessBuilder tool = ProcessTools.createJavaProcessBuilder(
-            "-XaddExports:jdk.hotspot.agent/sun.jvm.hotspot.oops=ALL-UNNAMED",
-            "-XaddExports:jdk.hotspot.agent/sun.jvm.hotspot.memory=ALL-UNNAMED",
-            "-XaddExports:jdk.hotspot.agent/sun.jvm.hotspot.runtime=ALL-UNNAMED",
-            "-XaddExports:jdk.hotspot.agent/sun.jvm.hotspot.tools=ALL-UNNAMED",
+            "--add-modules=jdk.hotspot.agent",
+            "--add-exports=jdk.hotspot.agent/sun.jvm.hotspot.oops=ALL-UNNAMED",
+            "--add-exports=jdk.hotspot.agent/sun.jvm.hotspot.memory=ALL-UNNAMED",
+            "--add-exports=jdk.hotspot.agent/sun.jvm.hotspot.runtime=ALL-UNNAMED",
+            "--add-exports=jdk.hotspot.agent/sun.jvm.hotspot.tools=ALL-UNNAMED",
             "SASymbolTableTestAgent",
             Long.toString(pid));
         OutputAnalyzer output = ProcessTools.executeProcess(tool);
--- a/hotspot/test/runtime/Unsafe/RangeCheck.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/hotspot/test/runtime/Unsafe/RangeCheck.java	Wed Jul 05 22:05:22 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -44,7 +44,7 @@
         ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
                 true,
                 "-Xmx32m",
-                "-XaddExports:java.base/jdk.internal.misc=ALL-UNNAMED",
+                "--add-exports=java.base/jdk.internal.misc=ALL-UNNAMED",
                 "-XX:-TransmitErrorReport",
                 "-XX:-CreateCoredumpOnCrash",
                 "-XX:-InlineUnsafeOps", // The compiler intrinsics doesn't have the assert
--- a/hotspot/test/runtime/getSysPackage/GetSysPkgTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/hotspot/test/runtime/getSysPackage/GetSysPkgTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -98,7 +98,7 @@
             ClassFileInstaller.writeClassToDisk("GetSysPkg_package/GetSysClass", klassbuf);
 
             ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-Xbootclasspath/a:bl_dir",
-                "-XaddExports:java.base/jdk.internal.loader=ALL-UNNAMED", "-cp", "." + File.pathSeparator +
+                "--add-exports=java.base/jdk.internal.loader=ALL-UNNAMED", "-cp", "." + File.pathSeparator +
                 System.getProperty("test.classes"), "GetSysPkgTest", "do_tests");
             OutputAnalyzer output = new OutputAnalyzer(pb.start());
             output.shouldHaveExitValue(0);
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/runtime/modules/IgnoreModulePropertiesTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -0,0 +1,75 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8136930
+ * @summary Test that the VM ignores explicitly specified module internal properties.
+ * @modules java.base/jdk.internal.misc
+ * @library /testlibrary
+ */
+
+import jdk.test.lib.*;
+
+// Test that the VM ignores module related properties such as "jdk.module.addmods"
+// and jdk.module.addreads.0" that can only be set using module options.
+public class IgnoreModulePropertiesTest {
+
+    // Test that the specified property and its value are ignored.  If the VM accepted
+    // the property and value then an exception would be thrown because the value is
+    // bogus for that property.  But, since the property is ignored no exception is
+    // thrown.
+    public static void testProperty(String prop, String value) throws Exception {
+        ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
+            "-D" + prop + "=" + value, "-version");
+        OutputAnalyzer output = new OutputAnalyzer(pb.start());
+        output.shouldContain("java version ");
+        output.shouldHaveExitValue(0);
+
+        // Ensure that the property and its value aren't available.
+        if (System.getProperty(prop) != null) {
+            throw new RuntimeException(
+                "Unexpected non-null value for property " + prop);
+        }
+    }
+
+    // For options of the form "option=value", check that an exception gets thrown for
+    // the illegal value and then check that its corresponding property is handled
+    // correctly.
+    public static void testOption(String option, String value,
+                                  String prop, String result) throws Exception {
+        ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
+            option + "=" + value, "-version");
+        OutputAnalyzer output = new OutputAnalyzer(pb.start());
+        output.shouldContain(result);
+        testProperty(prop, value);
+    }
+
+    public static void main(String[] args) throws Exception {
+        testOption("--add-modules", "java.sqlx", "jdk.module.addmods", "java.lang.module.ResolutionException");
+        testOption("--limit-modules", "java.sqlx", "jdk.module.limitmods", "java.lang.module.ResolutionException");
+        testOption("--add-reads", "xyzz=yyzd", "jdk.module.addreads.0", "java.lang.RuntimeException");
+        testOption("--add-exports", "java.base/xyzz=yyzd", "jdk.module.addexports.0", "java.lang.RuntimeException");
+        testOption("--patch-module", "=d", "jdk.module.patch.0", "IllegalArgumentException");
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/runtime/modules/ModuleOptionsTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8136930
+ * @summary Test that the VM only recognizes the last specified --add-modules
+ *          and --list-modules options
+ * @modules java.base/jdk.internal.misc
+ * @library /testlibrary
+ */
+
+import jdk.test.lib.*;
+
+// Test that the VM behaves correctly when processing module related options.
+public class ModuleOptionsTest {
+
+    public static void main(String[] args) throws Exception {
+
+        // Test that last --add-modules is the only one recognized.  No exception
+        // should be thrown.
+        ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
+            "--add-modules=i_dont_exist", "--add-modules=java.base", "-version");
+        OutputAnalyzer output = new OutputAnalyzer(pb.start());
+        output.shouldHaveExitValue(0);
+
+        // Test that last --limit-modules is the only one recognized.  No exception
+        // should be thrown.
+        pb = ProcessTools.createJavaProcessBuilder(
+            "--limit-modules=i_dont_exist", "--limit-modules=java.base", "-version");
+        output = new OutputAnalyzer(pb.start());
+        output.shouldHaveExitValue(0);
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/runtime/modules/ModuleOptionsWarn.java	Wed Jul 05 22:05:22 2017 +0200
@@ -0,0 +1,60 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8162415
+ * @summary Test warnings for ignored properties.
+ * @modules java.base/jdk.internal.misc
+ * @library /testlibrary
+ */
+
+import jdk.test.lib.*;
+
+// Test that the VM behaves correctly when processing command line module system properties.
+public class ModuleOptionsWarn {
+
+    public static void main(String[] args) throws Exception {
+
+        // Test that a warning is issued for module related properties that get ignored.
+        ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
+            "-XX:+PrintWarnings", "-Djdk.module.ignored", "-version");
+        OutputAnalyzer output = new OutputAnalyzer(pb.start());
+        output.shouldContain("Ignoring system property option");
+        output.shouldHaveExitValue(0);
+
+        // Test that a warning can be suppressed for module related properties that get ignored.
+        pb = ProcessTools.createJavaProcessBuilder(
+            "-Djdk.module.ignored", "-XX:-PrintWarnings", "-version");
+        output = new OutputAnalyzer(pb.start());
+        output.shouldNotContain("Ignoring system property option");
+        output.shouldHaveExitValue(0);
+
+        // Test that a warning is not issued for properties of the form "jdk.module.main"
+        pb = ProcessTools.createJavaProcessBuilder(
+            "-XX:+PrintWarnings", "-Djdk.module.main.ignored", "-version");
+        output = new OutputAnalyzer(pb.start());
+        output.shouldNotContain("Ignoring system property option");
+        output.shouldHaveExitValue(0);
+    }
+}
--- a/hotspot/test/runtime/modules/ModuleStress/ExportModuleStressTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/hotspot/test/runtime/modules/ModuleStress/ExportModuleStressTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -62,8 +62,8 @@
         compiled = CompilerUtils.compile(
             SRC_DIR.resolve("jdk.translet"),
             MODS_DIR.resolve("jdk.translet"),
-            "-XaddExports:jdk.test/test=jdk.translet",
-            "-mp", MODS_DIR.toString());
+            "--add-exports=jdk.test/test=jdk.translet",
+            "-p", MODS_DIR.toString());
         if (!compiled) {
             throw new RuntimeException("Test failed to compile module jdk.translet");
         }
@@ -71,7 +71,7 @@
         // Sanity check that the test, jdk.test/test/Main.java
         // runs without error.
         ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
-            "-mp", MODS_DIR.toString(),
+            "-p", MODS_DIR.toString(),
             "-m", "jdk.test/test.Main");
         OutputAnalyzer output = new OutputAnalyzer(pb.start());
         output.shouldContain("failed: 0")
--- a/hotspot/test/runtime/modules/ModuleStress/ModuleStressGC.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/hotspot/test/runtime/modules/ModuleStress/ModuleStressGC.java	Wed Jul 05 22:05:22 2017 +0200
@@ -62,8 +62,8 @@
         compiled = CompilerUtils.compile(
             SRC_DIR.resolve("jdk.translet"),
             MODS_DIR.resolve("jdk.translet"),
-            "-XaddExports:jdk.test/test=jdk.translet",
-            "-mp", MODS_DIR.toString());
+            "--add-exports=jdk.test/test=jdk.translet",
+            "-p", MODS_DIR.toString());
         if (!compiled) {
             throw new RuntimeException("Test failed to compile module jdk.translet");
         }
@@ -74,7 +74,7 @@
         // GC safepoints.
         ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
             "-Xlog:modules=trace",
-            "-mp", MODS_DIR.toString(),
+            "-p", MODS_DIR.toString(),
             "-m", "jdk.test/test.MainGC");
         OutputAnalyzer oa = new OutputAnalyzer(pb.start());
         oa.shouldContain("package test defined in module jdk.test, exports list being walked")
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/runtime/modules/PatchModule/BasicJarBuilder.java	Wed Jul 05 22:05:22 2017 +0200
@@ -0,0 +1,96 @@
+/*
+ * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @summary Simple jar builder
+ *   Input: jarName className1 className2 ...
+ *     do not specify extensions, just the names
+ *     E.g. prot_domain ProtDomainA ProtDomainB
+ *   Output: A jar containing compiled classes, placed in a test classes folder
+ */
+
+import jdk.test.lib.*;
+
+import java.io.File;
+import java.util.ArrayList;
+import sun.tools.jar.Main;
+
+// Using JarBuilder requires that all to-be-jarred classes should be placed
+// in the current working directory, aka "."
+public class BasicJarBuilder {
+    private static final String classDir = System.getProperty("test.classes");
+
+    public static void build(boolean classesInWorkDir, String jarName,
+        String ...classNames) throws Exception {
+
+        if (classesInWorkDir) {
+            createSimpleJar(".", classDir + File.separator + jarName + ".jar", classNames);
+        } else {
+            build(jarName, classNames);
+        }
+    }
+
+    public static void build(String jarName, String ...classNames) throws Exception {
+        createSimpleJar(classDir, classDir + File.separator + jarName + ".jar",
+            classNames);
+    }
+
+    private static void createSimpleJar(String jarclassDir, String jarName,
+        String[] classNames) throws Exception {
+        ArrayList<String> args = new ArrayList<String>();
+        args.add("cf");
+        args.add(jarName);
+        addClassArgs(args, jarclassDir, classNames);
+        createJar(args);
+    }
+
+    private static void addClassArgs(ArrayList<String> args, String jarclassDir,
+        String[] classNames) {
+
+        for (String name : classNames) {
+            args.add("-C");
+            args.add(jarclassDir);
+            args.add(name + ".class");
+        }
+    }
+
+    private static void createJar(ArrayList<String> args) {
+        Main jarTool = new Main(System.out, System.err, "jar");
+        if (!jarTool.run(args.toArray(new String[1]))) {
+            throw new RuntimeException("jar operation failed");
+        }
+    }
+
+    // Get full path to the test jar
+    public static String getTestJar(String jar) {
+        File dir = new File(System.getProperty("test.classes", "."));
+        File jarFile = new File(dir, jar);
+        if (!jarFile.exists()) {
+            throw new RuntimeException("Cannot find " + jarFile.getPath());
+        }
+        if (!jarFile.isFile()) {
+            throw new RuntimeException("Not a regular file: " + jarFile.getPath());
+        }
+        return jarFile.getPath();
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/runtime/modules/PatchModule/PatchModule2Dirs.java	Wed Jul 05 22:05:22 2017 +0200
@@ -0,0 +1,70 @@
+/*
+ * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @summary Make sure --patch-module works with multiple directories.
+ * @modules java.base/jdk.internal.misc
+ * @library /testlibrary
+ * @compile PatchModule2DirsMain.java
+ * @run main PatchModule2Dirs
+ */
+
+import jdk.test.lib.*;
+import java.io.File;
+
+public class PatchModule2Dirs {
+
+    public static void main(String[] args) throws Exception {
+        String source1 = "package javax.naming.spi; "               +
+                        "public class NamingManager { "             +
+                        "    static { "                             +
+                        "        System.out.println(\"I pass one!\"); " +
+                        "    } "                                    +
+                        "}";
+        String source2 = "package java.beans; "                     +
+                        "public class Encoder { "                   +
+                        "    static { "                             +
+                        "        System.out.println(\"I pass two!\"); " +
+                        "    } "                                    +
+                        "}";
+
+        ClassFileInstaller.writeClassToDisk("javax/naming/spi/NamingManager",
+             InMemoryJavaCompiler.compile("javax.naming.spi.NamingManager", source1, "-Xmodule:java.naming"),
+             "mods/java.naming");
+
+        ClassFileInstaller.writeClassToDisk("java/beans/Encoder",
+             InMemoryJavaCompiler.compile("java.beans.Encoder", source2, "-Xmodule:java.desktop"),
+             "mods2/java.desktop");
+
+        ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
+             "--patch-module=java.naming=mods/java.naming",
+             "--patch-module=java.desktop=mods2/java.desktop",
+             "PatchModule2DirsMain", "javax.naming.spi.NamingManager", "java.beans.Encoder");
+
+        OutputAnalyzer oa = new OutputAnalyzer(pb.start());
+        oa.shouldContain("I pass one!");
+        oa.shouldContain("I pass two!");
+        oa.shouldHaveExitValue(0);
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/runtime/modules/PatchModule/PatchModule2DirsMain.java	Wed Jul 05 22:05:22 2017 +0200
@@ -0,0 +1,31 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+// This loads the class affected by the --patch-module option.  For the test to pass
+// it must load both classes from the --patch-module directory, not the jimage file.
+public class PatchModule2DirsMain {
+    public static void main(String[] args) throws Exception {
+        Class.forName(args[0]);
+        Class.forName(args[1]);
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/runtime/modules/PatchModule/PatchModuleCDS.java	Wed Jul 05 22:05:22 2017 +0200
@@ -0,0 +1,62 @@
+/*
+ * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @library /testlibrary
+ * @modules java.base/jdk.internal.misc
+ * @run main PatchModuleCDS
+ */
+
+import java.io.File;
+import jdk.test.lib.*;
+
+public class PatchModuleCDS {
+
+    public static void main(String args[]) throws Throwable {
+        System.out.println("Test that --patch-module and -Xshare:dump are incompatibable");
+        ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("--patch-module=java.naming=mods/java.naming", "-Xshare:dump");
+        OutputAnalyzer output = new OutputAnalyzer(pb.start());
+        output.shouldContain("Cannot use the following option when dumping the shared archive: --patch-module");
+
+        System.out.println("Test that --patch-module and -Xshare:on are incompatibable");
+        String filename = "patch_module.jsa";
+        pb = ProcessTools.createJavaProcessBuilder(
+            "-XX:+UnlockDiagnosticVMOptions",
+            "-XX:SharedArchiveFile=" + filename,
+            "-Xshare:dump");
+        output = new OutputAnalyzer(pb.start());
+        output.shouldContain("ro space:"); // Make sure archive got created.
+
+        pb = ProcessTools.createJavaProcessBuilder(
+            "-XX:+UnlockDiagnosticVMOptions",
+            "-XX:SharedArchiveFile=" + filename,
+            "-Xshare:on",
+            "--patch-module=java.naming=mods/java.naming",
+            "-version");
+        output = new OutputAnalyzer(pb.start());
+        output.shouldContain("The shared archive file cannot be used with --patch-module");
+
+        output.shouldHaveExitValue(1);
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/runtime/modules/PatchModule/PatchModuleDupJavaBase.java	Wed Jul 05 22:05:22 2017 +0200
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @summary VM exit initialization results if java.base is specificed more than once to --patch-module.
+ * @modules java.base/jdk.internal.misc
+ * @library /testlibrary
+ */
+
+import jdk.test.lib.*;
+
+public class PatchModuleDupJavaBase {
+  // The VM should exit initialization if java.base is specified
+  // more than once to --patch-module.
+  public static void main(String args[]) throws Exception {
+    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
+      "--patch-module=java.base=javabase_dir",
+      "--patch-module=java.base=javabase_dir",
+      "-version");
+    OutputAnalyzer output = new OutputAnalyzer(pb.start());
+    output.shouldContain("Cannot specify java.base more than once to --patch-module");
+    output.shouldHaveExitValue(1);
+  }
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/runtime/modules/PatchModule/PatchModuleDupModule.java	Wed Jul 05 22:05:22 2017 +0200
@@ -0,0 +1,47 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @summary Module system initialization exception results if a module is specificed twice to --patch-module.
+ * @modules java.base/jdk.internal.misc
+ * @library /testlibrary
+ */
+
+import jdk.test.lib.*;
+
+public class PatchModuleDupModule {
+
+  // The module system initialization should generate an ExceptionInInitializerError
+  // if --patch-module is specified with the same module more than once.
+
+  public static void main(String args[]) throws Exception {
+    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
+      "--patch-module=module1=module1_dir",
+      "--patch-module=module1=module1_dir",
+      "-version");
+    OutputAnalyzer output = new OutputAnalyzer(pb.start());
+    output.shouldContain("java.lang.ExceptionInInitializerError");
+    output.shouldHaveExitValue(1);
+  }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/runtime/modules/PatchModule/PatchModuleJavaBase.java	Wed Jul 05 22:05:22 2017 +0200
@@ -0,0 +1,57 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8130399
+ * @summary Make sure --patch-module works for java.base.
+ * @modules java.base/jdk.internal.misc
+ * @library /testlibrary
+ * @compile PatchModuleMain.java
+ * @run main PatchModuleJavaBase
+ */
+
+import jdk.test.lib.*;
+
+public class PatchModuleJavaBase {
+
+    public static void main(String[] args) throws Exception {
+        String source = "package java.lang; "                       +
+                        "public class NewClass { "                  +
+                        "    static { "                             +
+                        "        System.out.println(\"I pass!\"); " +
+                        "    } "                                    +
+                        "}";
+
+        ClassFileInstaller.writeClassToDisk("java/lang/NewClass",
+             InMemoryJavaCompiler.compile("java.lang.NewClass", source, "-Xmodule:java.base"),
+             "mods/java.base");
+
+        ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("--patch-module=java.base=mods/java.base",
+             "PatchModuleMain", "java.lang.NewClass");
+
+        new OutputAnalyzer(pb.start())
+            .shouldContain("I pass!")
+            .shouldHaveExitValue(0);
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/runtime/modules/PatchModule/PatchModuleMain.java	Wed Jul 05 22:05:22 2017 +0200
@@ -0,0 +1,30 @@
+/*
+ * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+// This loads the class affected by the --patch-module option.  For the test to pass
+// it must load the class from the --patch-module directory, not the jimage file.
+public class PatchModuleMain {
+    public static void main(String[] args) throws Exception {
+        Class.forName(args[0]);
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/runtime/modules/PatchModule/PatchModuleTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -0,0 +1,57 @@
+/*
+ * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8130399
+ * @summary Make sure --patch-module works for modules besides java.base.
+ * @modules java.base/jdk.internal.misc
+ * @library /testlibrary
+ * @compile PatchModuleMain.java
+ * @run main PatchModuleTest
+ */
+
+import jdk.test.lib.*;
+
+public class PatchModuleTest {
+
+    public static void main(String[] args) throws Exception {
+        String source = "package javax.naming.spi; "                +
+                        "public class NamingManager { "             +
+                        "    static { "                             +
+                        "        System.out.println(\"I pass!\"); " +
+                        "    } "                                    +
+                        "}";
+
+        ClassFileInstaller.writeClassToDisk("javax/naming/spi/NamingManager",
+             InMemoryJavaCompiler.compile("javax.naming.spi.NamingManager", source, "-Xmodule:java.naming"),
+             "mods/java.naming");
+
+        ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("--patch-module=java.naming=mods/java.naming",
+             "PatchModuleMain", "javax.naming.spi.NamingManager");
+
+        new OutputAnalyzer(pb.start())
+            .shouldContain("I pass!")
+            .shouldHaveExitValue(0);
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/runtime/modules/PatchModule/PatchModuleTestJar.java	Wed Jul 05 22:05:22 2017 +0200
@@ -0,0 +1,83 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @summary Make sure --patch-module works when a jar file is specified for a module
+ * @library /testlibrary
+ * @modules java.base/jdk.internal.misc
+ *          jdk.jartool/sun.tools.jar
+ * @build BasicJarBuilder
+ * @compile PatchModuleMain.java
+ * @run main PatchModuleTestJar
+ */
+
+import jdk.test.lib.*;
+
+public class PatchModuleTestJar {
+    private static String moduleJar;
+
+    public static void main(String[] args) throws Exception {
+
+        // Create a class file in the module java.naming. This class file
+        // will be put in the javanaming.jar file.
+        String source = "package javax.naming.spi; "                +
+                        "public class NamingManager { "             +
+                        "    static { "                             +
+                        "        System.out.println(\"I pass!\"); " +
+                        "    } "                                    +
+                        "}";
+
+        ClassFileInstaller.writeClassToDisk("javax/naming/spi/NamingManager",
+             InMemoryJavaCompiler.compile("javax.naming.spi.NamingManager", source, "-Xmodule:java.naming"),
+             System.getProperty("test.classes"));
+
+        // Build the jar file that will be used for the module "java.naming".
+        BasicJarBuilder.build("javanaming", "javax/naming/spi/NamingManager");
+        moduleJar = BasicJarBuilder.getTestJar("javanaming.jar");
+
+        // Just to make sure we are not fooled by the class file being on the
+        // class path where all the test classes are stored, write the NamingManager.class
+        // file out again with output that does not contain what OutputAnalyzer
+        // expects. This will provide confidence that the contents of the class
+        // is truly coming from the jar file and not the class file.
+        source =        "package javax.naming.spi; "                +
+                        "public class NamingManager { "             +
+                        "    static { "                             +
+                        "        System.out.println(\"Fail!\"); "   +
+                        "    } "                                    +
+                        "}";
+
+        ClassFileInstaller.writeClassToDisk("javax/naming/spi/NamingManager",
+             InMemoryJavaCompiler.compile("javax.naming.spi.NamingManager", source, "-Xmodule:java.naming"),
+             System.getProperty("test.classes"));
+
+        // Supply --patch-module with the name of the jar file for the module java.naming.
+        ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("--patch-module=java.naming=" + moduleJar,
+             "PatchModuleMain", "javax.naming.spi.NamingManager");
+
+        new OutputAnalyzer(pb.start())
+            .shouldContain("I pass!")
+            .shouldHaveExitValue(0);
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/runtime/modules/PatchModule/PatchModuleTestJarDir.java	Wed Jul 05 22:05:22 2017 +0200
@@ -0,0 +1,105 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @summary Make sure --patch-module works when a jar file and a directory is specified for a module
+ * @library /testlibrary
+ * @modules java.base/jdk.internal.misc
+ *          jdk.jartool/sun.tools.jar
+ * @build BasicJarBuilder
+ * @compile PatchModule2DirsMain.java
+ * @run main PatchModuleTestJarDir
+ */
+
+import java.io.File;
+import java.nio.file.Files;
+import jdk.test.lib.*;
+
+public class PatchModuleTestJarDir {
+    private static String moduleJar;
+
+    public static void main(String[] args) throws Exception {
+
+        // Create a class file in the module java.naming. This class file
+        // will be put in the javanaming.jar file.
+        String source = "package javax.naming.spi; "                    +
+                        "public class NamingManager1 { "                +
+                        "    static { "                                 +
+                        "        System.out.println(\"I pass one!\"); " +
+                        "    } "                                        +
+                        "}";
+
+        ClassFileInstaller.writeClassToDisk("javax/naming/spi/NamingManager1",
+             InMemoryJavaCompiler.compile("javax.naming.spi.NamingManager1", source, "-Xmodule:java.naming"),
+             System.getProperty("test.classes"));
+
+        // Build the jar file that will be used for the module "java.naming".
+        BasicJarBuilder.build("javanaming", "javax/naming/spi/NamingManager1");
+        moduleJar = BasicJarBuilder.getTestJar("javanaming.jar");
+
+        // Just to make sure we are not fooled by the class file being on the
+        // class path where all the test classes are stored, write the NamingManager.class
+        // file out again with output that does not contain what OutputAnalyzer
+        // expects. This will provide confidence that the contents of the class
+        // is truly coming from the jar file and not the class file.
+        source = "package javax.naming.spi; "                +
+                 "public class NamingManager1 { "            +
+                 "    static { "                             +
+                 "        System.out.println(\"Fail!\"); "   +
+                 "    } "                                    +
+                 "}";
+
+        ClassFileInstaller.writeClassToDisk("javax/naming/spi/NamingManager1",
+             InMemoryJavaCompiler.compile("javax.naming.spi.NamingManager1", source, "-Xmodule:java.naming"),
+             System.getProperty("test.classes"));
+
+        // Create a second class file in the module java.naming. This class file
+        // will be put in the mods/java.naming directory.
+        source = "package javax.naming.spi; "                    +
+                 "public class NamingManager2 { "                +
+                 "    static { "                                 +
+                 "        System.out.println(\"I pass two!\"); " +
+                 "    } "                                        +
+                 "}";
+
+        ClassFileInstaller.writeClassToDisk("javax/naming/spi/NamingManager2",
+             InMemoryJavaCompiler.compile("javax.naming.spi.NamingManager2", source, "-Xmodule:java.naming"),
+             (System.getProperty("test.classes") + "/mods/java.naming"));
+
+
+        // Supply --patch-module with the name of the jar file for the module java.naming.
+        ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("--patch-module=java.naming=" +
+                                                                           moduleJar +
+                                                                           File.pathSeparator +
+                                                                           System.getProperty("test.classes") + "/mods/java.naming",
+                                                                  "PatchModule2DirsMain",
+                                                                  "javax.naming.spi.NamingManager1",
+                                                                  "javax.naming.spi.NamingManager2");
+
+        new OutputAnalyzer(pb.start())
+            .shouldContain("I pass one!")
+            .shouldContain("I pass two!")
+            .shouldHaveExitValue(0);
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/runtime/modules/PatchModule/PatchModuleTraceCL.java	Wed Jul 05 22:05:22 2017 +0200
@@ -0,0 +1,83 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8069469
+ * @summary Make sure -Xlog:classload=info works properly with "modules" jimage,
+            --patch-module, and with -Xbootclasspath/a
+ * @modules java.base/jdk.internal.misc
+ * @library /testlibrary
+ * @compile PatchModuleMain.java
+ * @run main PatchModuleTraceCL
+ */
+
+import java.io.File;
+import jdk.test.lib.*;
+
+public class PatchModuleTraceCL {
+
+    public static void main(String[] args) throws Exception {
+        String source = "package javax.naming.spi; "                +
+                        "public class NamingManager { "             +
+                        "    static { "                             +
+                        "        System.out.println(\"I pass!\"); " +
+                        "    } "                                    +
+                        "}";
+
+        // Test -Xlog:classload=info output for --patch-module
+        ClassFileInstaller.writeClassToDisk("javax/naming/spi/NamingManager",
+             InMemoryJavaCompiler.compile("javax.naming.spi.NamingManager", source, "-Xmodule:java.naming"),
+             "mods/java.naming");
+
+        ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("--patch-module=java.naming=mods/java.naming",
+             "-Xlog:class+load=info", "PatchModuleMain", "javax.naming.spi.NamingManager");
+
+        OutputAnalyzer output = new OutputAnalyzer(pb.start());
+        // "modules" jimage case.
+        output.shouldContain("[class,load] java.lang.Thread source: jrt:/java.base");
+        // --patch-module case.
+        output.shouldContain("[class,load] javax.naming.spi.NamingManager source: mods/java.naming");
+        // -cp case.
+        output.shouldContain("[class,load] PatchModuleMain source: file");
+
+        // Test -Xlog:classload=info output for -Xbootclasspath/a
+        source = "package PatchModuleTraceCL_pkg; "                 +
+                 "public class ItIsI { "                          +
+                 "    static { "                                  +
+                 "        System.out.println(\"I also pass!\"); " +
+                 "    } "                                         +
+                 "}";
+
+        ClassFileInstaller.writeClassToDisk("PatchModuleTraceCL_pkg/ItIsI",
+             InMemoryJavaCompiler.compile("PatchModuleTraceCL_pkg.ItIsI", source),
+             "xbcp");
+
+        pb = ProcessTools.createJavaProcessBuilder("-Xbootclasspath/a:xbcp",
+             "-Xlog:class+load=info", "PatchModuleMain", "PatchModuleTraceCL_pkg.ItIsI");
+        output = new OutputAnalyzer(pb.start());
+        // -Xbootclasspath/a case.
+        output.shouldContain("[class,load] PatchModuleTraceCL_pkg.ItIsI source: xbcp");
+        output.shouldHaveExitValue(0);
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/runtime/modules/Visibility/PatchModuleVisibility.java	Wed Jul 05 22:05:22 2017 +0200
@@ -0,0 +1,91 @@
+/*
+ * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @summary Ensure that a newly introduced java.base package placed within the --patch-module
+ *          directory is considered part of the boot loader's visibility boundary
+ * @requires !(os.family == "windows")
+ * @library /testlibrary
+ * @modules java.base/jdk.internal.misc
+ *          java.management
+ * @run main/othervm PatchModuleVisibility
+ */
+
+import java.io.File;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+
+import jdk.test.lib.*;
+
+public class PatchModuleVisibility {
+
+    public static void main(String[] args) throws Throwable {
+
+      String Vis2_B_src =
+              "package p2;" +
+              "public class Vis2_B {" +
+              "    public void m() {" +
+              "        System.out.println(\"In B's m()\");" +
+              "    }" +
+              "}";
+
+      String Vis2_A_src =
+              "import p2.*;" +
+              "public class Vis2_A {" +
+              "    public static void main(String args[]) throws Exception {" +
+                      // Try loading a class within a newly introduced java.base
+                      // package.  Make sure the class can be found via --patch-module.
+              "        try {" +
+              "            p2.Vis2_B b = new p2.Vis2_B();" +
+              "            if (b.getClass().getClassLoader() != null) {" +
+              "                throw new RuntimeException(\"PatchModuleVisibility FAILED - class B " +
+                                                           "should be loaded by boot class loader\\n\");" +
+              "            }" +
+              "            b.m();" +
+              "        } catch (Throwable e) {" +
+              "            throw new RuntimeException(\"PatchModuleVisibility FAILED - test " +
+                                                       "should not throw an error or exception\\n\");" +
+              "        }" +
+              "        System.out.println(\"PatchModuleVisibility PASSED\\n\");" +
+              "    }" +
+              "}";
+
+      ClassFileInstaller.writeClassToDisk("p2/Vis2_B",
+          InMemoryJavaCompiler.compile("p2.Vis2_B", Vis2_B_src), System.getProperty("test.classes"));
+      ClassFileInstaller.writeClassToDisk("p2/Vis2_B", "mods2/java.base");
+
+      ClassFileInstaller.writeClassToDisk("Vis2_A",
+          InMemoryJavaCompiler.compile("Vis2_A", Vis2_A_src), System.getProperty("test.classes"));
+
+      // Make sure the classes are actually being loaded from mods2
+      Files.delete(Paths.get(System.getProperty("test.classes") +  File.separator +
+                                                           "p2" + File.separator + "Vis2_B.class"));
+
+      new OutputAnalyzer(ProcessTools.createJavaProcessBuilder(
+              "--patch-module=java.base=mods2/java.base",
+              "--add-exports=java.base/p2=ALL-UNNAMED",
+              "Vis2_A")
+          .start()).shouldHaveExitValue(0);
+    }
+}
--- a/hotspot/test/runtime/modules/Visibility/XbootcpNoVisibility.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/hotspot/test/runtime/modules/Visibility/XbootcpNoVisibility.java	Wed Jul 05 22:05:22 2017 +0200
@@ -50,7 +50,7 @@
                         // Try loading a class within a named package in a module which has been defined
                         // to the boot loader. In this situation, the class should only be attempted
                         // to be loaded from the boot loader's module path which consists of:
-                        //   [-Xpatch]; exploded build | "modules" jimage
+                        //   [--patch-module]; exploded build | "modules" jimage
                         //
                         // Since the class is located on the boot loader's append path via
                         // -Xbootclasspath/a specification, it should not be found.
--- a/hotspot/test/runtime/modules/Visibility/XpatchVisibility.java	Mon Aug 15 08:28:26 2016 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,91 +0,0 @@
-/*
- * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-/*
- * @test
- * @summary Ensure that a newly introduced java.base package placed within the -Xpatch directory
- *          is considered part of the boot loader's visibility boundary
- * @requires !(os.family == "windows")
- * @library /testlibrary
- * @modules java.base/jdk.internal.misc
- *          java.management
- * @run main/othervm XpatchVisibility
- */
-
-import java.io.File;
-import java.nio.file.Files;
-import java.nio.file.Paths;
-
-import jdk.test.lib.*;
-
-public class XpatchVisibility {
-
-    public static void main(String[] args) throws Throwable {
-
-      String Vis2_B_src =
-              "package p2;" +
-              "public class Vis2_B {" +
-              "    public void m() {" +
-              "        System.out.println(\"In B's m()\");" +
-              "    }" +
-              "}";
-
-      String Vis2_A_src =
-              "import p2.*;" +
-              "public class Vis2_A {" +
-              "    public static void main(String args[]) throws Exception {" +
-                      // Try loading a class within a newly introduced java.base
-                      // package.  Make sure the class can be found via -Xpatch.
-              "        try {" +
-              "            p2.Vis2_B b = new p2.Vis2_B();" +
-              "            if (b.getClass().getClassLoader() != null) {" +
-              "                throw new RuntimeException(\"XpatchVisibility FAILED - class B " +
-                                                           "should be loaded by boot class loader\\n\");" +
-              "            }" +
-              "            b.m();" +
-              "        } catch (Throwable e) {" +
-              "            throw new RuntimeException(\"XpatchVisibility FAILED - test " +
-                                                       "should not throw an error or exception\\n\");" +
-              "        }" +
-              "        System.out.println(\"XpatchVisibility PASSED\\n\");" +
-              "    }" +
-              "}";
-
-      ClassFileInstaller.writeClassToDisk("p2/Vis2_B",
-          InMemoryJavaCompiler.compile("p2.Vis2_B", Vis2_B_src), System.getProperty("test.classes"));
-      ClassFileInstaller.writeClassToDisk("p2/Vis2_B", "mods2/java.base");
-
-      ClassFileInstaller.writeClassToDisk("Vis2_A",
-          InMemoryJavaCompiler.compile("Vis2_A", Vis2_A_src), System.getProperty("test.classes"));
-
-      // Make sure the classes are actually being loaded from mods2
-      Files.delete(Paths.get(System.getProperty("test.classes") +  File.separator +
-                                                           "p2" + File.separator + "Vis2_B.class"));
-
-      new OutputAnalyzer(ProcessTools.createJavaProcessBuilder(
-              "-Xpatch:java.base=mods2/java.base",
-              "-XaddExports:java.base/p2=ALL-UNNAMED",
-              "Vis2_A")
-          .start()).shouldHaveExitValue(0);
-    }
-}
--- a/hotspot/test/runtime/modules/Xpatch/BasicJarBuilder.java	Mon Aug 15 08:28:26 2016 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,96 +0,0 @@
-/*
- * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-/*
- * @summary Simple jar builder
- *   Input: jarName className1 className2 ...
- *     do not specify extensions, just the names
- *     E.g. prot_domain ProtDomainA ProtDomainB
- *   Output: A jar containing compiled classes, placed in a test classes folder
- */
-
-import jdk.test.lib.*;
-
-import java.io.File;
-import java.util.ArrayList;
-import sun.tools.jar.Main;
-
-// Using JarBuilder requires that all to-be-jarred classes should be placed
-// in the current working directory, aka "."
-public class BasicJarBuilder {
-    private static final String classDir = System.getProperty("test.classes");
-
-    public static void build(boolean classesInWorkDir, String jarName,
-        String ...classNames) throws Exception {
-
-        if (classesInWorkDir) {
-            createSimpleJar(".", classDir + File.separator + jarName + ".jar", classNames);
-        } else {
-            build(jarName, classNames);
-        }
-    }
-
-    public static void build(String jarName, String ...classNames) throws Exception {
-        createSimpleJar(classDir, classDir + File.separator + jarName + ".jar",
-            classNames);
-    }
-
-    private static void createSimpleJar(String jarclassDir, String jarName,
-        String[] classNames) throws Exception {
-        ArrayList<String> args = new ArrayList<String>();
-        args.add("cf");
-        args.add(jarName);
-        addClassArgs(args, jarclassDir, classNames);
-        createJar(args);
-    }
-
-    private static void addClassArgs(ArrayList<String> args, String jarclassDir,
-        String[] classNames) {
-
-        for (String name : classNames) {
-            args.add("-C");
-            args.add(jarclassDir);
-            args.add(name + ".class");
-        }
-    }
-
-    private static void createJar(ArrayList<String> args) {
-        Main jarTool = new Main(System.out, System.err, "jar");
-        if (!jarTool.run(args.toArray(new String[1]))) {
-            throw new RuntimeException("jar operation failed");
-        }
-    }
-
-    // Get full path to the test jar
-    public static String getTestJar(String jar) {
-        File dir = new File(System.getProperty("test.classes", "."));
-        File jarFile = new File(dir, jar);
-        if (!jarFile.exists()) {
-            throw new RuntimeException("Cannot find " + jarFile.getPath());
-        }
-        if (!jarFile.isFile()) {
-            throw new RuntimeException("Not a regular file: " + jarFile.getPath());
-        }
-        return jarFile.getPath();
-    }
-}
--- a/hotspot/test/runtime/modules/Xpatch/Xpatch2Dirs.java	Mon Aug 15 08:28:26 2016 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,70 +0,0 @@
-/*
- * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-/*
- * @test
- * @summary Make sure -Xpatch works with multiple directories.
- * @modules java.base/jdk.internal.misc
- * @library /testlibrary
- * @compile Xpatch2DirsMain.java
- * @run main Xpatch2Dirs
- */
-
-import jdk.test.lib.*;
-import java.io.File;
-
-public class Xpatch2Dirs {
-
-    public static void main(String[] args) throws Exception {
-        String source1 = "package javax.naming.spi; "               +
-                        "public class NamingManager { "             +
-                        "    static { "                             +
-                        "        System.out.println(\"I pass one!\"); " +
-                        "    } "                                    +
-                        "}";
-        String source2 = "package java.beans; "                     +
-                        "public class Encoder { "                   +
-                        "    static { "                             +
-                        "        System.out.println(\"I pass two!\"); " +
-                        "    } "                                    +
-                        "}";
-
-        ClassFileInstaller.writeClassToDisk("javax/naming/spi/NamingManager",
-             InMemoryJavaCompiler.compile("javax.naming.spi.NamingManager", source1, "-Xmodule:java.naming"),
-             "mods/java.naming");
-
-        ClassFileInstaller.writeClassToDisk("java/beans/Encoder",
-             InMemoryJavaCompiler.compile("java.beans.Encoder", source2, "-Xmodule:java.desktop"),
-             "mods2/java.desktop");
-
-        ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
-             "-Xpatch:java.naming=mods/java.naming",
-             "-Xpatch:java.desktop=mods2/java.desktop",
-             "Xpatch2DirsMain", "javax.naming.spi.NamingManager", "java.beans.Encoder");
-
-        OutputAnalyzer oa = new OutputAnalyzer(pb.start());
-        oa.shouldContain("I pass one!");
-        oa.shouldContain("I pass two!");
-        oa.shouldHaveExitValue(0);
-    }
-}
--- a/hotspot/test/runtime/modules/Xpatch/Xpatch2DirsMain.java	Mon Aug 15 08:28:26 2016 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,31 +0,0 @@
-/*
- * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-// This loads the class affected by the -Xpatch option.  For the test to pass
-// it must load both classes from the -Xpatch directory, not the jimage file.
-public class Xpatch2DirsMain {
-    public static void main(String[] args) throws Exception {
-        Class.forName(args[0]);
-        Class.forName(args[1]);
-    }
-}
--- a/hotspot/test/runtime/modules/Xpatch/XpatchDupJavaBase.java	Mon Aug 15 08:28:26 2016 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,46 +0,0 @@
-/*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-/*
- * @test
- * @summary VM exit initialization results if java.base is specificed more than once to Xpatch.
- * @modules java.base/jdk.internal.misc
- * @library /testlibrary
- */
-
-import jdk.test.lib.*;
-
-public class XpatchDupJavaBase {
-  // The VM should exit initialization if java.base is specified
-  // more than once to -Xpatch.
-  public static void main(String args[]) throws Exception {
-    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
-      "-Xpatch:java.base=javabase_dir",
-      "-Xpatch:java.base=javabase_dir",
-      "-version");
-    OutputAnalyzer output = new OutputAnalyzer(pb.start());
-    output.shouldContain("Cannot specify java.base more than once to -Xpatch");
-    output.shouldHaveExitValue(1);
-  }
-}
-
--- a/hotspot/test/runtime/modules/Xpatch/XpatchDupModule.java	Mon Aug 15 08:28:26 2016 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,48 +0,0 @@
-/*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-/*
- * @test
- * @summary Module system initialization exception results if a module is specificed twice to Xpatch.
- * @modules java.base/jdk.internal.misc
- * @library /testlibrary
- */
-
-import jdk.test.lib.*;
-
-public class XpatchDupModule {
-
-  // The module system initialization should generate an ExceptionInInitializerError
-  // if -Xpatch is specified with the same module more than once.
-
-  public static void main(String args[]) throws Exception {
-    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
-      "-Xpatch:module1=module1_dir",
-      "-Xpatch:module1=module1_dir",
-      "-version");
-    OutputAnalyzer output = new OutputAnalyzer(pb.start());
-    output.shouldContain("java.lang.ExceptionInInitializerError");
-    output.shouldHaveExitValue(1);
-  }
-}
-
--- a/hotspot/test/runtime/modules/Xpatch/XpatchJavaBase.java	Mon Aug 15 08:28:26 2016 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,57 +0,0 @@
-/*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-/*
- * @test
- * @bug 8130399
- * @summary Make sure -Xpatch works for java.base.
- * @modules java.base/jdk.internal.misc
- * @library /testlibrary
- * @compile XpatchMain.java
- * @run main XpatchJavaBase
- */
-
-import jdk.test.lib.*;
-
-public class XpatchJavaBase {
-
-    public static void main(String[] args) throws Exception {
-        String source = "package java.lang; "                       +
-                        "public class NewClass { "                  +
-                        "    static { "                             +
-                        "        System.out.println(\"I pass!\"); " +
-                        "    } "                                    +
-                        "}";
-
-        ClassFileInstaller.writeClassToDisk("java/lang/NewClass",
-             InMemoryJavaCompiler.compile("java.lang.NewClass", source, "-Xmodule:java.base"),
-             "mods/java.base");
-
-        ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-Xpatch:java.base=mods/java.base",
-             "XpatchMain", "java.lang.NewClass");
-
-        new OutputAnalyzer(pb.start())
-            .shouldContain("I pass!")
-            .shouldHaveExitValue(0);
-    }
-}
--- a/hotspot/test/runtime/modules/Xpatch/XpatchMain.java	Mon Aug 15 08:28:26 2016 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,30 +0,0 @@
-/*
- * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-// This loads the class affected by the -Xpatch option.  For the test to pass
-// it must load the class from the -Xpatch directory, not the jimage file.
-public class XpatchMain {
-    public static void main(String[] args) throws Exception {
-        Class.forName(args[0]);
-    }
-}
--- a/hotspot/test/runtime/modules/Xpatch/XpatchTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,57 +0,0 @@
-/*
- * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-/*
- * @test
- * @bug 8130399
- * @summary Make sure -Xpatch works for modules besides java.base.
- * @modules java.base/jdk.internal.misc
- * @library /testlibrary
- * @compile XpatchMain.java
- * @run main XpatchTest
- */
-
-import jdk.test.lib.*;
-
-public class XpatchTest {
-
-    public static void main(String[] args) throws Exception {
-        String source = "package javax.naming.spi; "                +
-                        "public class NamingManager { "             +
-                        "    static { "                             +
-                        "        System.out.println(\"I pass!\"); " +
-                        "    } "                                    +
-                        "}";
-
-        ClassFileInstaller.writeClassToDisk("javax/naming/spi/NamingManager",
-             InMemoryJavaCompiler.compile("javax.naming.spi.NamingManager", source, "-Xmodule:java.naming"),
-             "mods/java.naming");
-
-        ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-Xpatch:java.naming=mods/java.naming",
-             "XpatchMain", "javax.naming.spi.NamingManager");
-
-        new OutputAnalyzer(pb.start())
-            .shouldContain("I pass!")
-            .shouldHaveExitValue(0);
-    }
-}
--- a/hotspot/test/runtime/modules/Xpatch/XpatchTestJar.java	Mon Aug 15 08:28:26 2016 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,83 +0,0 @@
-/*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-/*
- * @test
- * @summary Make sure -Xpatch works when a jar file is specified for a module
- * @library /testlibrary
- * @modules java.base/jdk.internal.misc
- *          jdk.jartool/sun.tools.jar
- * @build BasicJarBuilder
- * @compile XpatchMain.java
- * @run main XpatchTestJar
- */
-
-import jdk.test.lib.*;
-
-public class XpatchTestJar {
-    private static String moduleJar;
-
-    public static void main(String[] args) throws Exception {
-
-        // Create a class file in the module java.naming. This class file
-        // will be put in the javanaming.jar file.
-        String source = "package javax.naming.spi; "                +
-                        "public class NamingManager { "             +
-                        "    static { "                             +
-                        "        System.out.println(\"I pass!\"); " +
-                        "    } "                                    +
-                        "}";
-
-        ClassFileInstaller.writeClassToDisk("javax/naming/spi/NamingManager",
-             InMemoryJavaCompiler.compile("javax.naming.spi.NamingManager", source, "-Xmodule:java.naming"),
-             System.getProperty("test.classes"));
-
-        // Build the jar file that will be used for the module "java.naming".
-        BasicJarBuilder.build("javanaming", "javax/naming/spi/NamingManager");
-        moduleJar = BasicJarBuilder.getTestJar("javanaming.jar");
-
-        // Just to make sure we are not fooled by the class file being on the
-        // class path where all the test classes are stored, write the NamingManager.class
-        // file out again with output that does not contain what OutputAnalyzer
-        // expects. This will provide confidence that the contents of the class
-        // is truly coming from the jar file and not the class file.
-        source =        "package javax.naming.spi; "                +
-                        "public class NamingManager { "             +
-                        "    static { "                             +
-                        "        System.out.println(\"Fail!\"); "   +
-                        "    } "                                    +
-                        "}";
-
-        ClassFileInstaller.writeClassToDisk("javax/naming/spi/NamingManager",
-             InMemoryJavaCompiler.compile("javax.naming.spi.NamingManager", source, "-Xmodule:java.naming"),
-             System.getProperty("test.classes"));
-
-        // Supply -Xpatch with the name of the jar file for the module java.naming.
-        ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-Xpatch:java.naming=" + moduleJar,
-             "XpatchMain", "javax.naming.spi.NamingManager");
-
-        new OutputAnalyzer(pb.start())
-            .shouldContain("I pass!")
-            .shouldHaveExitValue(0);
-    }
-}
--- a/hotspot/test/runtime/modules/Xpatch/XpatchTestJarDir.java	Mon Aug 15 08:28:26 2016 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,105 +0,0 @@
-/*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-/*
- * @test
- * @summary Make sure -Xpatch works when a jar file and a directory is specified for a module
- * @library /testlibrary
- * @modules java.base/jdk.internal.misc
- *          jdk.jartool/sun.tools.jar
- * @build BasicJarBuilder
- * @compile Xpatch2DirsMain.java
- * @run main XpatchTestJarDir
- */
-
-import java.io.File;
-import java.nio.file.Files;
-import jdk.test.lib.*;
-
-public class XpatchTestJarDir {
-    private static String moduleJar;
-
-    public static void main(String[] args) throws Exception {
-
-        // Create a class file in the module java.naming. This class file
-        // will be put in the javanaming.jar file.
-        String source = "package javax.naming.spi; "                    +
-                        "public class NamingManager1 { "                +
-                        "    static { "                                 +
-                        "        System.out.println(\"I pass one!\"); " +
-                        "    } "                                        +
-                        "}";
-
-        ClassFileInstaller.writeClassToDisk("javax/naming/spi/NamingManager1",
-             InMemoryJavaCompiler.compile("javax.naming.spi.NamingManager1", source, "-Xmodule:java.naming"),
-             System.getProperty("test.classes"));
-
-        // Build the jar file that will be used for the module "java.naming".
-        BasicJarBuilder.build("javanaming", "javax/naming/spi/NamingManager1");
-        moduleJar = BasicJarBuilder.getTestJar("javanaming.jar");
-
-        // Just to make sure we are not fooled by the class file being on the
-        // class path where all the test classes are stored, write the NamingManager.class
-        // file out again with output that does not contain what OutputAnalyzer
-        // expects. This will provide confidence that the contents of the class
-        // is truly coming from the jar file and not the class file.
-        source = "package javax.naming.spi; "                +
-                 "public class NamingManager1 { "            +
-                 "    static { "                             +
-                 "        System.out.println(\"Fail!\"); "   +
-                 "    } "                                    +
-                 "}";
-
-        ClassFileInstaller.writeClassToDisk("javax/naming/spi/NamingManager1",
-             InMemoryJavaCompiler.compile("javax.naming.spi.NamingManager1", source, "-Xmodule:java.naming"),
-             System.getProperty("test.classes"));
-
-        // Create a second class file in the module java.naming. This class file
-        // will be put in the mods/java.naming directory.
-        source = "package javax.naming.spi; "                    +
-                 "public class NamingManager2 { "                +
-                 "    static { "                                 +
-                 "        System.out.println(\"I pass two!\"); " +
-                 "    } "                                        +
-                 "}";
-
-        ClassFileInstaller.writeClassToDisk("javax/naming/spi/NamingManager2",
-             InMemoryJavaCompiler.compile("javax.naming.spi.NamingManager2", source, "-Xmodule:java.naming"),
-             (System.getProperty("test.classes") + "/mods/java.naming"));
-
-
-        // Supply -Xpatch with the name of the jar file for the module java.naming.
-        ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-Xpatch:java.naming=" +
-                                                                           moduleJar +
-                                                                           File.pathSeparator +
-                                                                           System.getProperty("test.classes") + "/mods/java.naming",
-                                                                  "Xpatch2DirsMain",
-                                                                  "javax.naming.spi.NamingManager1",
-                                                                  "javax.naming.spi.NamingManager2");
-
-        new OutputAnalyzer(pb.start())
-            .shouldContain("I pass one!")
-            .shouldContain("I pass two!")
-            .shouldHaveExitValue(0);
-    }
-}
--- a/hotspot/test/runtime/modules/Xpatch/XpatchTraceCL.java	Mon Aug 15 08:28:26 2016 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,83 +0,0 @@
-/*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-/*
- * @test
- * @bug 8069469
- * @summary Make sure -Xlog:classload=info works properly with "modules" jimage,
-            -Xpatch, and with -Xbootclasspath/a
- * @modules java.base/jdk.internal.misc
- * @library /testlibrary
- * @compile XpatchMain.java
- * @run main XpatchTraceCL
- */
-
-import java.io.File;
-import jdk.test.lib.*;
-
-public class XpatchTraceCL {
-
-    public static void main(String[] args) throws Exception {
-        String source = "package javax.naming.spi; "                +
-                        "public class NamingManager { "             +
-                        "    static { "                             +
-                        "        System.out.println(\"I pass!\"); " +
-                        "    } "                                    +
-                        "}";
-
-        // Test -Xlog:classload=info output for -Xpatch
-        ClassFileInstaller.writeClassToDisk("javax/naming/spi/NamingManager",
-             InMemoryJavaCompiler.compile("javax.naming.spi.NamingManager", source, "-Xmodule:java.naming"),
-             "mods/java.naming");
-
-        ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-Xpatch:java.naming=mods/java.naming",
-             "-Xlog:class+load=info", "XpatchMain", "javax.naming.spi.NamingManager");
-
-        OutputAnalyzer output = new OutputAnalyzer(pb.start());
-        // "modules" jimage case.
-        output.shouldContain("[class,load] java.lang.Thread source: jrt:/java.base");
-        // -Xpatch case.
-        output.shouldContain("[class,load] javax.naming.spi.NamingManager source: mods/java.naming");
-        // -cp case.
-        output.shouldContain("[class,load] XpatchMain source: file");
-
-        // Test -Xlog:classload=info output for -Xbootclasspath/a
-        source = "package XpatchTraceCL_pkg; "                 +
-                 "public class ItIsI { "                          +
-                 "    static { "                                  +
-                 "        System.out.println(\"I also pass!\"); " +
-                 "    } "                                         +
-                 "}";
-
-        ClassFileInstaller.writeClassToDisk("XpatchTraceCL_pkg/ItIsI",
-             InMemoryJavaCompiler.compile("XpatchTraceCL_pkg.ItIsI", source),
-             "xbcp");
-
-        pb = ProcessTools.createJavaProcessBuilder("-Xbootclasspath/a:xbcp",
-             "-Xlog:class+load=info", "XpatchMain", "XpatchTraceCL_pkg.ItIsI");
-        output = new OutputAnalyzer(pb.start());
-        // -Xbootclasspath/a case.
-        output.shouldContain("[class,load] XpatchTraceCL_pkg.ItIsI source: xbcp");
-        output.shouldHaveExitValue(0);
-    }
-}
--- a/hotspot/test/runtime/modules/XpatchCDS.java	Mon Aug 15 08:28:26 2016 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,62 +0,0 @@
-/*
- * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-/*
- * @test
- * @library /testlibrary
- * @modules java.base/jdk.internal.misc
- * @run main XpatchCDS
- */
-
-import java.io.File;
-import jdk.test.lib.*;
-
-public class XpatchCDS {
-
-    public static void main(String args[]) throws Throwable {
-        System.out.println("Test that -Xpatch and -Xshare:dump are incompatibable");
-        ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-Xpatch:java.naming=mods/java.naming", "-Xshare:dump");
-        OutputAnalyzer output = new OutputAnalyzer(pb.start());
-        output.shouldContain("Cannot use the following option when dumping the shared archive: -Xpatch");
-
-        System.out.println("Test that -Xpatch and -Xshare:on are incompatibable");
-        String filename = "Xpatch.jsa";
-        pb = ProcessTools.createJavaProcessBuilder(
-            "-XX:+UnlockDiagnosticVMOptions",
-            "-XX:SharedArchiveFile=" + filename,
-            "-Xshare:dump");
-        output = new OutputAnalyzer(pb.start());
-        output.shouldContain("ro space:"); // Make sure archive got created.
-
-        pb = ProcessTools.createJavaProcessBuilder(
-            "-XX:+UnlockDiagnosticVMOptions",
-            "-XX:SharedArchiveFile=" + filename,
-            "-Xshare:on",
-            "-Xpatch:java.naming=mods/java.naming",
-            "-version");
-        output = new OutputAnalyzer(pb.start());
-        output.shouldContain("The shared archive file cannot be used with -Xpatch");
-
-        output.shouldHaveExitValue(1);
-    }
-}
--- a/hotspot/test/runtime/modules/java.base/java/lang/reflect/ModuleHelper.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/hotspot/test/runtime/modules/java.base/java/lang/reflect/ModuleHelper.java	Wed Jul 05 22:05:22 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,7 +27,7 @@
 
 /**
  * A helper class intended to be injected into java.lang.reflect using the
- * java -Xpatch option. The helper class provides access to package private
+ * java --patch-module option. The helper class provides access to package private
  * methods in java.lang.reflect.Module.
  */
 
--- a/hotspot/test/serviceability/sa/TestInstanceKlassSize.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/hotspot/test/serviceability/sa/TestInstanceKlassSize.java	Wed Jul 05 22:05:22 2017 +0200
@@ -113,9 +113,10 @@
                                           };
             String[] toolArgs = {
                 "-XX:+UnlockDiagnosticVMOptions",
-                "-XaddExports:jdk.hotspot.agent/sun.jvm.hotspot=ALL-UNNAMED",
-                "-XaddExports:jdk.hotspot.agent/sun.jvm.hotspot.utilities=ALL-UNNAMED",
-                "-XaddExports:jdk.hotspot.agent/sun.jvm.hotspot.oops=ALL-UNNAMED",
+                "--add-modules=jdk.hotspot.agent",
+                "--add-exports=jdk.hotspot.agent/sun.jvm.hotspot=ALL-UNNAMED",
+                "--add-exports=jdk.hotspot.agent/sun.jvm.hotspot.utilities=ALL-UNNAMED",
+                "--add-exports=jdk.hotspot.agent/sun.jvm.hotspot.oops=ALL-UNNAMED",
                 "TestInstanceKlassSize",
                 Long.toString(app.getPid())
             };
--- a/hotspot/test/serviceability/sa/TestInstanceKlassSizeForInterface.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/hotspot/test/serviceability/sa/TestInstanceKlassSizeForInterface.java	Wed Jul 05 22:05:22 2017 +0200
@@ -107,9 +107,10 @@
         // Grab the pid from the current java process and pass it
         String[] toolArgs = {
             "-XX:+UnlockDiagnosticVMOptions",
-            "-XaddExports:jdk.hotspot.agent/sun.jvm.hotspot=ALL-UNNAMED",
-            "-XaddExports:jdk.hotspot.agent/sun.jvm.hotspot.utilities=ALL-UNNAMED",
-            "-XaddExports:jdk.hotspot.agent/sun.jvm.hotspot.oops=ALL-UNNAMED",
+            "--add-modules=jdk.hotspot.agent",
+            "--add-exports=jdk.hotspot.agent/sun.jvm.hotspot=ALL-UNNAMED",
+            "--add-exports=jdk.hotspot.agent/sun.jvm.hotspot.utilities=ALL-UNNAMED",
+            "--add-exports=jdk.hotspot.agent/sun.jvm.hotspot.oops=ALL-UNNAMED",
             "TestInstanceKlassSizeForInterface",
             Long.toString(ProcessTools.getProcessId())
         };
--- a/hotspot/test/serviceability/sa/jmap-hprof/JMapHProfLargeHeapTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/hotspot/test/serviceability/sa/jmap-hprof/JMapHProfLargeHeapTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -87,7 +87,7 @@
             String expectedFormat) throws Exception, IOException,
             InterruptedException, FileNotFoundException {
         ProcessBuilder procBuilder = ProcessTools.createJavaProcessBuilder(
-                "-XaddExports:java.management/sun.management=ALL-UNNAMED", vmArgs, "JMapHProfLargeHeapProc", String.valueOf(heapSize));
+                "--add-exports=java.management/sun.management=ALL-UNNAMED", vmArgs, "JMapHProfLargeHeapProc", String.valueOf(heapSize));
         procBuilder.redirectError(ProcessBuilder.Redirect.INHERIT);
         Process largeHeapProc = procBuilder.start();
 
--- a/hotspot/test/testlibrary/ctw/Makefile	Mon Aug 15 08:28:26 2016 +0200
+++ b/hotspot/test/testlibrary/ctw/Makefile	Wed Jul 05 22:05:22 2017 +0200
@@ -58,10 +58,10 @@
 
 ctw.jar: filelist wb.jar
 	@mkdir -p $(OUTPUT_DIR)
-	$(JAVAC) -XaddExports:java.base/jdk.internal.jimage=ALL-UNNAMED \
-		-XaddExports:java.base/jdk.internal.misc=ALL-UNNAMED \
-		-XaddExports:java.base/jdk.internal.reflect=ALL-UNNAMED \
-		-sourcepath $(SRC_DIR) -d $(OUTPUT_DIR) -cp wb.jar @filelist
+	$(JAVAC) --add-exports java.base/jdk.internal.jimage=ALL-UNNAMED \
+		 --add-exports java.base/jdk.internal.misc=ALL-UNNAMED \
+		 --add-exports java.base/jdk.internal.reflect=ALL-UNNAMED \
+		 -sourcepath $(SRC_DIR) -d $(OUTPUT_DIR) -cp wb.jar @filelist
 	$(JAR) --create --file=$@ --main-class $(MAIN_CLASS) -C $(OUTPUT_DIR) .
 
 wb.jar: wb_filelist
--- a/hotspot/test/testlibrary/jittester/Makefile	Mon Aug 15 08:28:26 2016 +0200
+++ b/hotspot/test/testlibrary/jittester/Makefile	Wed Jul 05 22:05:22 2017 +0200
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -95,10 +95,10 @@
 	@echo 'Main-Class: jdk.test.lib.jittester.Automatic' >> $(MANIFEST)
 
 compile_testlib: INIT
-	$(JAVAC) -XDignore.symbol.file -XaddExports:java.base/jdk.internal.misc=ALL-UNNAMED -XaddExports:java.base/jdk.internal.org.objectweb.asm=ALL-UNNAMED -Xlint $(TESTLIBRARY_SRC_FILES) -d $(CLASSES_DIR)
+	$(JAVAC) -XDignore.symbol.file --add-exports=java.base/jdk.internal.misc=ALL-UNNAMED --add-exports=java.base/jdk.internal.org.objectweb.asm=ALL-UNNAMED -Xlint $(TESTLIBRARY_SRC_FILES) -d $(CLASSES_DIR)
 
 COMPILE: INIT filelist compile_testlib
-	$(JAVAC) -cp $(CLASSES_DIR) -XDignore.symbol.file -XaddExports:java.base/jdk.internal.misc=ALL-UNNAMED -XaddExports:java.base/jdk.internal.org.objectweb.asm=ALL-UNNAMED -Xlint -sourcepath $(SRC_DIR) -d $(CLASSES_DIR) @filelist
+	$(JAVAC) -cp $(CLASSES_DIR) -XDignore.symbol.file --add-exports=java.base/jdk.internal.misc=ALL-UNNAMED --add-exports=java.base/jdk.internal.org.objectweb.asm=ALL-UNNAMED -Xlint -sourcepath $(SRC_DIR) -d $(CLASSES_DIR) @filelist
 
 filelist: $(SRC_FILES)
 		@rm -f $@
@@ -109,7 +109,7 @@
 	$(shell if [ ! -d $(CLASSES_DIR) ]; then mkdir -p $(CLASSES_DIR); fi)
 
 install: clean_testbase testgroup testroot copytestlibrary JAR cleantmp
-	$(JAVA) -XaddExports:java.base/jdk.internal.org.objectweb.asm=ALL-UNNAMED -ea -jar $(DIST_JAR) $(APPLICATION_ARGS)
+	$(JAVA) --add-exports=java.base/jdk.internal.org.objectweb.asm=ALL-UNNAMED -ea -jar $(DIST_JAR) $(APPLICATION_ARGS)
 
 clean_testbase:
 	@rm -rf $(TESTBASE_DIR)
--- a/jaxp/.hgtags	Mon Aug 15 08:28:26 2016 +0200
+++ b/jaxp/.hgtags	Wed Jul 05 22:05:22 2017 +0200
@@ -373,3 +373,4 @@
 8a7681a9d70640ac7fbf05c28f53c1d51d8d00a1 jdk-9+128
 74241304e87b0d463391a8ecab40979b5af86dc2 jdk-9+129
 e66cdc2de6b02443911d386fc9217b0d824d0686 jdk-9+130
+874082a9b565a7092a40bfa934a6e3e3c3455a60 jdk-9+131
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xpath/regex/message.properties	Mon Aug 15 08:28:26 2016 +0200
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xpath/regex/message.properties	Wed Jul 05 22:05:22 2017 +0200
@@ -37,5 +37,3 @@
 parser.quantifier.3=Invalid quantifier. A digit or '}' is expected.
 parser.quantifier.4=Invalid quantifier. A min quantity must be <= a max quantity.
 parser.quantifier.5=Invalid quantifier. A quantity value overflow.
-null
-null
--- a/jaxp/test/TEST.ROOT	Mon Aug 15 08:28:26 2016 +0200
+++ b/jaxp/test/TEST.ROOT	Wed Jul 05 22:05:22 2017 +0200
@@ -23,4 +23,7 @@
 groups=TEST.groups
 
 # Minimum jtreg version
-requiredVersion=4.2 b02
+requiredVersion=4.2 b03
+
+# Use new module options
+useNewOptions=true
--- a/jaxp/test/javax/xml/jaxp/libs/jaxp/library/BasePolicy.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jaxp/test/javax/xml/jaxp/libs/jaxp/library/BasePolicy.java	Wed Jul 05 22:05:22 2017 +0200
@@ -37,7 +37,7 @@
         try {
             JAXPPolicyManager.teardownPolicyManager();
         } catch (Exception e) {
-            throw new RuntimeException("Failed to teardonw the policy manager", e);
+            throw new RuntimeException("Failed to teardown the policy manager", e);
         }
     }
 
--- a/jaxp/test/javax/xml/jaxp/unittest/catalog/CatalogSupport2.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jaxp/test/javax/xml/jaxp/unittest/catalog/CatalogSupport2.java	Wed Jul 05 22:05:22 2017 +0200
@@ -28,10 +28,8 @@
 import static jaxp.library.JAXPTestUtilities.setSystemProperty;
 
 import java.io.File;
-import java.io.FileNotFoundException;
+import java.io.IOException;
 import java.io.StringReader;
-import java.net.SocketTimeoutException;
-
 import javax.xml.transform.Source;
 import javax.xml.transform.TransformerException;
 import javax.xml.transform.URIResolver;
@@ -52,7 +50,7 @@
 
 /*
  * @test
- * @bug 8158084 8162438 8162442
+ * @bug 8158084 8162438 8162442 8163535
  * @library /javax/xml/jaxp/libs /javax/xml/jaxp/unittest
  * @run testng/othervm -DrunSecMngr=true catalog.CatalogSupport2
  * @run testng/othervm catalog.CatalogSupport2
@@ -97,7 +95,7 @@
     /*
        Verifies the Catalog support on SAXParser.
     */
-    @Test(dataProvider = "data_SAXC", expectedExceptions = FileNotFoundException.class)
+    @Test(dataProvider = "data_SAXC", expectedExceptions = IOException.class)
     public void testSAXC(boolean setUseCatalog, boolean useCatalog, String catalog, String
             xml, MyHandler handler, String expected) throws Exception {
         testSAX(setUseCatalog, useCatalog, catalog, xml, handler, expected);
@@ -106,7 +104,7 @@
     /*
        Verifies the Catalog support on XMLReader.
     */
-    @Test(dataProvider = "data_SAXC", expectedExceptions = FileNotFoundException.class)
+    @Test(dataProvider = "data_SAXC", expectedExceptions = IOException.class)
     public void testXMLReaderC(boolean setUseCatalog, boolean useCatalog, String catalog,
             String xml, MyHandler handler, String expected) throws Exception {
         testXMLReader(setUseCatalog, useCatalog, catalog, xml, handler, expected);
@@ -124,7 +122,7 @@
     /*
        Verifies the Catalog support on DOM parser.
     */
-    @Test(dataProvider = "data_DOMC", expectedExceptions = {FileNotFoundException.class, SocketTimeoutException.class})
+    @Test(dataProvider = "data_DOMC", expectedExceptions = IOException.class)
     public void testDOMC(boolean setUseCatalog, boolean useCatalog, String catalog,
             String xml, MyHandler handler, String expected) throws Exception {
         testDOM(setUseCatalog, useCatalog, catalog, xml, handler, expected);
@@ -141,7 +139,7 @@
         testValidation(setUseCatalog, useCatalog, catalog, xsd, resolver) ;
     }
 
-    @Test(dataProvider = "data_ValidatorC", expectedExceptions = {SAXException.class, FileNotFoundException.class})
+    @Test(dataProvider = "data_ValidatorC", expectedExceptions = {SAXException.class, IOException.class})
     public void testValidatorC(boolean setUseCatalog1, boolean setUseCatalog2, boolean useCatalog,
             Source source, LSResourceResolver resolver1, LSResourceResolver resolver2,
             String catalog1, String catalog2)
--- a/jaxp/test/javax/xml/jaxp/unittest/catalog/CatalogSupport3.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jaxp/test/javax/xml/jaxp/unittest/catalog/CatalogSupport3.java	Wed Jul 05 22:05:22 2017 +0200
@@ -27,10 +27,8 @@
 import static jaxp.library.JAXPTestUtilities.setSystemProperty;
 
 import java.io.File;
-import java.io.FileNotFoundException;
+import java.io.IOException;
 import java.io.StringReader;
-import java.net.SocketTimeoutException;
-
 import javax.xml.transform.Source;
 import javax.xml.transform.TransformerException;
 import javax.xml.transform.URIResolver;
@@ -51,7 +49,7 @@
 
 /*
  * @test
- * @bug 8158084 8162438 8162442
+ * @bug 8158084 8162438 8162442 8163535
  * @library /javax/xml/jaxp/libs /javax/xml/jaxp/unittest
  * @run testng/othervm -DrunSecMngr=true catalog.CatalogSupport3
  * @run testng/othervm catalog.CatalogSupport3
@@ -93,7 +91,7 @@
     /*
        Verifies the Catalog support on SAXParser.
     */
-    @Test(dataProvider = "data_SAXC", expectedExceptions = FileNotFoundException.class)
+    @Test(dataProvider = "data_SAXC", expectedExceptions = IOException.class)
     public void testSAXC(boolean setUseCatalog, boolean useCatalog, String catalog,
             String xml, MyHandler handler, String expected) throws Exception {
         testSAX(setUseCatalog, useCatalog, catalog, xml, handler, expected);
@@ -102,7 +100,7 @@
     /*
        Verifies the Catalog support on XMLReader.
     */
-    @Test(dataProvider = "data_SAXC", expectedExceptions = FileNotFoundException.class)
+    @Test(dataProvider = "data_SAXC", expectedExceptions = IOException.class)
     public void testXMLReaderC(boolean setUseCatalog, boolean useCatalog, String catalog,
             String xml, MyHandler handler, String expected) throws Exception {
         testXMLReader(setUseCatalog, useCatalog, catalog, xml, handler, expected);
@@ -120,7 +118,7 @@
     /*
        Verifies the Catalog support on DOM parser.
     */
-    @Test(dataProvider = "data_DOMC", expectedExceptions = {FileNotFoundException.class, SocketTimeoutException.class})
+    @Test(dataProvider = "data_DOMC", expectedExceptions = IOException.class)
     public void testDOMC(boolean setUseCatalog, boolean useCatalog, String catalog,
             String xml, MyHandler handler, String expected) throws Exception {
         testDOM(setUseCatalog, useCatalog, catalog, xml, handler, expected);
@@ -141,7 +139,7 @@
        @bug 8158084 8162438 these tests also verifies the fix for 8162438
        Verifies the Catalog support on the Schema Validator.
     */
-    @Test(dataProvider = "data_ValidatorC", expectedExceptions = {SAXException.class, FileNotFoundException.class})
+    @Test(dataProvider = "data_ValidatorC", expectedExceptions = {SAXException.class, IOException.class})
     public void testValidatorC(boolean setUseCatalog1, boolean setUseCatalog2, boolean useCatalog,
             Source source, LSResourceResolver resolver1, LSResourceResolver resolver2,
             String catalog1, String catalog2)
--- a/jaxp/test/javax/xml/jaxp/unittest/validation/Bug6773084Test.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jaxp/test/javax/xml/jaxp/unittest/validation/Bug6773084Test.java	Wed Jul 05 22:05:22 2017 +0200
@@ -32,11 +32,10 @@
 import java.util.concurrent.CyclicBarrier;
 import java.util.concurrent.ExecutorService;
 import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
 
 import javax.xml.XMLConstants;
-import javax.xml.parsers.DocumentBuilder;
 import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.parsers.ParserConfigurationException;
 import javax.xml.transform.Source;
 import javax.xml.transform.dom.DOMSource;
 import javax.xml.transform.stream.StreamSource;
@@ -69,6 +68,7 @@
     private static final ExecutorService EXEC = Executors.newCachedThreadPool();
 
     private static final CyclicBarrier BARRIER = new CyclicBarrier(NTHREADS);
+    private static final int TIMEOUT = 110;
 
     public static final String IN_FOLDER = Bug6773084Test.class.getResource("Bug6773084In").getPath();
     public static final String XSD_PATH = Bug6773084Test.class.getResource("Bug6773084.xsd").getPath();
@@ -93,20 +93,23 @@
             }
         });
 
+        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
+        dbf.setNamespaceAware(true);
+
         for (int i = 0; i < files.length; i++) {
-            EXEC.execute(new XMLValiddator(files[i], i));
+            EXEC.execute(new XMLValiddator(dbf.newDocumentBuilder().parse(files[i]), i));
         }
         runWithAllPerm(() -> EXEC.shutdown());
-
+        EXEC.awaitTermination(TIMEOUT, TimeUnit.SECONDS);
     }
 
     private static class XMLValiddator implements Runnable {
 
-        private File file;
+        private Document document;
         private int index;
 
-        public XMLValiddator(File file, int index) {
-            this.file = file;
+        public XMLValiddator(Document document, int index) {
+            this.document = document;
             this.index = index;
         }
 
@@ -117,23 +120,14 @@
                 BARRIER.await();
                 System.out.println("Validating....");
 
-                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
-                factory.setNamespaceAware(true);
-
-                DocumentBuilder builder = factory.newDocumentBuilder();
-                Document document = builder.parse(file);
-
                 Validator validator = schema.newValidator();
                 validator.setErrorHandler(new ErrorHandlerImpl());
                 validator.validate(new DOMSource(document));
-
             } catch (IOException e) {
                 e.printStackTrace();
             } catch (SAXException e) {
                 e.printStackTrace();
                 Assert.fail("Test failed.");
-            } catch (ParserConfigurationException e) {
-                e.printStackTrace();
             } catch (BrokenBarrierException e) {
                 e.printStackTrace();
             } catch (InterruptedException e) {
--- a/jaxws/.hgtags	Mon Aug 15 08:28:26 2016 +0200
+++ b/jaxws/.hgtags	Wed Jul 05 22:05:22 2017 +0200
@@ -376,3 +376,4 @@
 fe4e11bd2423635dc0f5f5cb9a64eb2f2cce7f4c jdk-9+128
 46a02f57218e4a8c334dbccf656fb048f823f163 jdk-9+129
 39c6293131d91aec7f2f5120395e070a937b8858 jdk-9+130
+783e7e2c587f2c7e1b9998a46d90ec196ab2a195 jdk-9+131
--- a/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/jxc/SchemaGenerator.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/jxc/SchemaGenerator.java	Wed Jul 05 22:05:22 2017 +0200
@@ -140,7 +140,7 @@
         aptargs.add("-cp");
         aptargs.add(setClasspath(options.classpath)); // set original classpath + jaxb-api to be visible to annotation processor
 
-        aptargs.add("-addmods");
+        aptargs.add("--add-modules");
         aptargs.add("java.xml.bind");
 
         if(options.targetDir!=null) {
--- a/jaxws/src/jdk.xml.ws/share/classes/com/sun/tools/internal/ws/wscompile/WsgenTool.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jaxws/src/jdk.xml.ws/share/classes/com/sun/tools/internal/ws/wscompile/WsgenTool.java	Wed Jul 05 22:05:22 2017 +0200
@@ -162,7 +162,7 @@
         boolean bootCP = useBootClasspath(EndpointReference.class) || useBootClasspath(XmlSeeAlso.class);
         List<String> args = new ArrayList<String>(6 + (bootCP ? 1 : 0) + (options.nocompile ? 1 : 0)
                 + (options.encoding != null ? 2 : 0));
-        args.add("-addmods");
+        args.add("--add-modules");
         args.add("java.xml.ws");
         args.add("-d");
         args.add(options.destDir.getAbsolutePath());
--- a/jaxws/src/jdk.xml.ws/share/classes/com/sun/tools/internal/ws/wscompile/WsimportTool.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jaxws/src/jdk.xml.ws/share/classes/com/sun/tools/internal/ws/wscompile/WsimportTool.java	Wed Jul 05 22:05:22 2017 +0200
@@ -525,7 +525,7 @@
             String classpathString = createClasspathString();
             boolean bootCP = useBootClasspath(EndpointContext.class) || useBootClasspath(JAXBPermission.class);
             List<String> args = new ArrayList<String>();
-            args.add("-addmods");
+            args.add("--add-modules");
             args.add("java.xml.ws");
             args.add("-d");
             args.add(classDir);
--- a/jdk/.hgtags	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/.hgtags	Wed Jul 05 22:05:22 2017 +0200
@@ -373,3 +373,4 @@
 9446c534f0222b4eecfd9d9e25ab37c4fd4400a5 jdk-9+128
 47699aa2e69ec2702542dc73eb01de3bfb61aea0 jdk-9+129
 6c827500e34587061af97ad6fef0e859280255c5 jdk-9+130
+8c57f4c293bbc5609928308a6d91ba765760b5f9 jdk-9+131
--- a/jdk/make/GenerateModuleSummary.gmk	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/make/GenerateModuleSummary.gmk	Wed Jul 05 22:05:22 2017 +0200
@@ -42,6 +42,6 @@
 
 $(GENGRAPHS_DIR)/module-summary.html: $(BUILD_JIGSAW_TOOLS) $(GENGRAPHS_DIR)/technology-summary.html
 	$(MKDIR) -p $(@D)
-	$(TOOL_MODULESUMMARY) -o $@ -mp $(IMAGES_OUTPUTDIR)/jmods
+	$(TOOL_MODULESUMMARY) -o $@ --module-path $(IMAGES_OUTPUTDIR)/jmods
 
 all: $(GENGRAPHS_DIR)/jdk.dot $(GENGRAPHS_DIR)/module-summary.html
--- a/jdk/make/ModuleTools.gmk	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/make/ModuleTools.gmk	Wed Jul 05 22:05:22 2017 +0200
@@ -36,12 +36,12 @@
     INCLUDES := build/tools/deps \
                 build/tools/jigsaw, \
     BIN := $(TOOLS_CLASSES_DIR), \
-    ADD_JAVAC_FLAGS := -XaddExports:jdk.jdeps/com.sun.tools.classfile=ALL-UNNAMED ))
+    ADD_JAVAC_FLAGS := --add-exports jdk.jdeps/com.sun.tools.classfile=ALL-UNNAMED ))
 
 
 TOOL_GENGRAPHS := $(BUILD_JAVA) -esa -ea -cp $(TOOLS_CLASSES_DIR) \
     build.tools.jigsaw.GenGraphs
 
 TOOL_MODULESUMMARY := $(BUILD_JAVA) -esa -ea -cp $(TOOLS_CLASSES_DIR) \
-    -XaddExports:jdk.jdeps/com.sun.tools.classfile=ALL-UNNAMED \
+    --add-exports jdk.jdeps/com.sun.tools.classfile=ALL-UNNAMED \
     build.tools.jigsaw.ModuleSummary
--- a/jdk/make/Tools.gmk	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/make/Tools.gmk	Wed Jul 05 22:05:22 2017 +0200
@@ -38,7 +38,7 @@
 ################################################################################
 
 ifeq ($(BOOT_JDK_MODULAR), true)
-  COMPILEFONTCONFIG_ADD_EXPORTS := -XaddExports:java.desktop/sun.awt=ALL-UNNAMED
+  COMPILEFONTCONFIG_ADD_EXPORTS := --add-exports java.desktop/sun.awt=ALL-UNNAMED
 endif
 
 TOOL_COMPILEFONTCONFIG = $(JAVA_SMALL) -cp $(BUILDTOOLS_OUTPUTDIR)/jdk_tools_classes \
@@ -94,7 +94,7 @@
 # Nimbus is used somewhere in the swing build.
 
 ifeq ($(BOOT_JDK_MODULAR), true)
-  COMPILENIMBUS_ADD_MODS := -addmods java.xml.bind
+  COMPILENIMBUS_ADD_MODS := --add-modules java.xml.bind
 endif
 
 TOOL_GENERATENIMBUS = $(JAVA_SMALL) -cp $(BUILDTOOLS_OUTPUTDIR)/jdk_tools_classes \
--- a/jdk/make/copy/Copy-java.base.gmk	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/make/copy/Copy-java.base.gmk	Wed Jul 05 22:05:22 2017 +0200
@@ -203,7 +203,7 @@
 ################################################################################
 
 ifeq ($(CACERTS_FILE), )
-  CACERTS_FILE := $(JDK_TOPDIR)/src/java.base/share/conf/security/cacerts
+  CACERTS_FILE := $(JDK_TOPDIR)/src/java.base/share/lib/security/cacerts
 endif
 
 CACERTS_DST := $(LIB_DST_DIR)/security/cacerts
--- a/jdk/make/gendata/GendataBreakIterator.gmk	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/make/gendata/GendataBreakIterator.gmk	Wed Jul 05 22:05:22 2017 +0200
@@ -63,11 +63,11 @@
 
 ifeq ($(BOOT_JDK_MODULAR), true)
   BREAK_ITERATOR_BOOTCLASSPATH := \
-      -Xpatch:java.base=$(BREAK_ITERATOR_CLASSES)/java.base \
-      -Xpatch:jdk.localedata=$(BREAK_ITERATOR_CLASSES)/jdk.localedata \
-      -XaddExports:java.base/sun.text=ALL-UNNAMED \
-      -XaddExports:java.base/sun.text.resources=ALL-UNNAMED \
-      -XaddExports:jdk.localedata/sun.text.resources.ext=ALL-UNNAMED \
+      --patch-module java.base=$(BREAK_ITERATOR_CLASSES)/java.base \
+      --patch-module jdk.localedata=$(BREAK_ITERATOR_CLASSES)/jdk.localedata \
+      --add-exports java.base/sun.text=ALL-UNNAMED \
+      --add-exports java.base/sun.text.resources=ALL-UNNAMED \
+      --add-exports jdk.localedata/sun.text.resources.ext=ALL-UNNAMED \
       #
 else
   BREAK_ITERATOR_BOOTCLASSPATH := -Xbootclasspath/p:$(call PathList, \
--- a/jdk/make/launcher/Launcher-java.desktop.gmk	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/make/launcher/Launcher-java.desktop.gmk	Wed Jul 05 22:05:22 2017 +0200
@@ -31,7 +31,7 @@
 ifndef BUILD_HEADLESS_ONLY
   $(eval $(call SetupBuildLauncher, appletviewer, \
       MAIN_CLASS := sun.applet.Main, \
-      JAVA_ARGS := -addmods ALL-DEFAULT, \
+      JAVA_ARGS := --add-modules ALL-DEFAULT, \
       LIBS_unix := $(X_LIBS), \
   ))
 endif
--- a/jdk/make/launcher/Launcher-java.scripting.gmk	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/make/launcher/Launcher-java.scripting.gmk	Wed Jul 05 22:05:22 2017 +0200
@@ -27,5 +27,5 @@
 
 $(eval $(call SetupBuildLauncher, jrunscript, \
     MAIN_CLASS := com.sun.tools.script.shell.Main, \
-    JAVA_ARGS := -addmods ALL-DEFAULT, \
+    JAVA_ARGS := --add-modules ALL-DEFAULT, \
 ))
--- a/jdk/make/launcher/Launcher-jdk.compiler.gmk	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/make/launcher/Launcher-jdk.compiler.gmk	Wed Jul 05 22:05:22 2017 +0200
@@ -27,7 +27,7 @@
 
 $(eval $(call SetupBuildLauncher, javac, \
    MAIN_CLASS := com.sun.tools.javac.Main, \
-   JAVA_ARGS := -addmods ALL-DEFAULT, \
+   JAVA_ARGS := --add-modules ALL-DEFAULT, \
    CFLAGS := -DEXPAND_CLASSPATH_WILDCARDS \
         -DNEVER_ACT_AS_SERVER_CLASS_MACHINE, \
 ))
--- a/jdk/make/launcher/Launcher-jdk.javadoc.gmk	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/make/launcher/Launcher-jdk.javadoc.gmk	Wed Jul 05 22:05:22 2017 +0200
@@ -27,7 +27,7 @@
 
 $(eval $(call SetupBuildLauncher, javadoc, \
     MAIN_CLASS := jdk.javadoc.internal.tool.Main, \
-    JAVA_ARGS := -addmods ALL-DEFAULT, \
+    JAVA_ARGS := --add-modules ALL-DEFAULT, \
     CFLAGS := -DEXPAND_CLASSPATH_WILDCARDS \
         -DNEVER_ACT_AS_SERVER_CLASS_MACHINE, \
 ))
--- a/jdk/make/launcher/Launcher-jdk.jlink.gmk	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/make/launcher/Launcher-jdk.jlink.gmk	Wed Jul 05 22:05:22 2017 +0200
@@ -32,7 +32,7 @@
 
 $(eval $(call SetupBuildLauncher, jlink,\
     MAIN_CLASS := jdk.tools.jlink.internal.Main, \
-    JAVA_ARGS := -addmods ALL-DEFAULT, \
+    JAVA_ARGS :=  --add-modules ALL-DEFAULT, \
     CFLAGS := -DENABLE_ARG_FILES \
         -DEXPAND_CLASSPATH_WILDCARDS \
         -DNEVER_ACT_AS_SERVER_CLASS_MACHINE, \
--- a/jdk/make/launcher/Launcher-jdk.scripting.nashorn.shell.gmk	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/make/launcher/Launcher-jdk.scripting.nashorn.shell.gmk	Wed Jul 05 22:05:22 2017 +0200
@@ -27,6 +27,6 @@
 
 $(eval $(call SetupBuildLauncher, jjs, \
     MAIN_CLASS := jdk.nashorn.tools.jjs.Main, \
-    JAVA_ARGS := -addmods ALL-DEFAULT, \
+    JAVA_ARGS := --add-modules ALL-DEFAULT, \
     CFLAGS := -DENABLE_ARG_FILES, \
 ))
--- a/jdk/make/src/classes/build/tools/jigsaw/ModuleSummary.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/make/src/classes/build/tools/jigsaw/ModuleSummary.java	Wed Jul 05 22:05:22 2017 +0200
@@ -51,7 +51,7 @@
 import static build.tools.jigsaw.ModuleSummary.HtmlDocument.Division.*;
 
 public class ModuleSummary {
-    private static final String USAGE = "Usage: ModuleSummary -mp <dir> -o <outfile> [-root mn]*";
+    private static final String USAGE = "Usage: ModuleSummary --module-path <dir> -o <outfile> [--root mn]*";
 
     public static void main(String[] args) throws Exception {
         int i=0;
@@ -61,13 +61,13 @@
         while (i < args.length && args[i].startsWith("-")) {
             String arg = args[i++];
             switch (arg) {
-                case "-mp":
+                case "--module-path":
                     modpath = Paths.get(args[i++]);
                     break;
                 case "-o":
                     outfile = Paths.get(args[i++]);
                     break;
-                case "-root":
+                case "--root":
                     roots.add(args[i++]);
                 default:
                     System.err.println(USAGE);
--- a/jdk/src/java.base/share/classes/com/sun/crypto/provider/HmacCore.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/src/java.base/share/classes/com/sun/crypto/provider/HmacCore.java	Wed Jul 05 22:05:22 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -53,10 +53,37 @@
     private final int blockLen;
 
     /**
-     * Standard constructor, creates a new HmacCore instance using the
-     * specified MessageDigest object.
+     * Standard constructor, creates a new HmacCore instance instantiating
+     * a MessageDigest of the specified name.
      */
-    HmacCore(MessageDigest md, int bl) {
+    HmacCore(String digestAlgo, int bl) throws NoSuchAlgorithmException {
+        MessageDigest md = MessageDigest.getInstance(digestAlgo);
+        if (!(md instanceof Cloneable)) {
+            // use SUN provider if the most preferred one does not support
+            // cloning
+            Provider sun = Security.getProvider("SUN");
+            if (sun != null) {
+                md = MessageDigest.getInstance(digestAlgo, sun);
+            } else {
+                String noCloneProv = md.getProvider().getName();
+                // if no Sun provider, use provider list
+                Provider[] provs = Security.getProviders();
+                for (Provider p : provs) {
+                    try {
+                        if (!p.getName().equals(noCloneProv)) {
+                            MessageDigest md2 =
+                                MessageDigest.getInstance(digestAlgo, p);
+                            if (md2 instanceof Cloneable) {
+                                md = md2;
+                                break;
+                            }
+                        }
+                    } catch (NoSuchAlgorithmException nsae) {
+                        continue;
+                    }
+                }
+            }
+        }
         this.md = md;
         this.blockLen = bl;
         this.k_ipad = new byte[blockLen];
@@ -65,14 +92,6 @@
     }
 
     /**
-     * Standard constructor, creates a new HmacCore instance instantiating
-     * a MessageDigest of the specified name.
-     */
-    HmacCore(String digestAlgorithm, int bl) throws NoSuchAlgorithmException {
-        this(MessageDigest.getInstance(digestAlgorithm), bl);
-    }
-
-    /**
      * Returns the length of the HMAC in bytes.
      *
      * @return the HMAC length in bytes.
--- a/jdk/src/java.base/share/classes/java/io/CharArrayReader.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/src/java.base/share/classes/java/io/CharArrayReader.java	Wed Jul 05 22:05:22 2017 +0200
@@ -131,8 +131,10 @@
             if (pos >= count) {
                 return -1;
             }
-            if (pos + len > count) {
-                len = count - pos;
+
+            int avail = count - pos;
+            if (len > avail) {
+                len = avail;
             }
             if (len <= 0) {
                 return 0;
@@ -158,8 +160,10 @@
     public long skip(long n) throws IOException {
         synchronized (lock) {
             ensureOpen();
-            if (pos + n > count) {
-                n = count - pos;
+
+            long avail = count - pos;
+            if (n > avail) {
+                n = avail;
             }
             if (n < 0) {
                 return 0;
--- a/jdk/src/java.base/share/classes/java/io/StringBufferInputStream.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/src/java.base/share/classes/java/io/StringBufferInputStream.java	Wed Jul 05 22:05:22 2017 +0200
@@ -118,8 +118,10 @@
         if (pos >= count) {
             return -1;
         }
-        if (pos + len > count) {
-            len = count - pos;
+
+        int avail = count - pos;
+        if (len > avail) {
+            len = avail;
         }
         if (len <= 0) {
             return 0;
--- a/jdk/src/java.base/share/classes/java/lang/System.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/src/java.base/share/classes/java/lang/System.java	Wed Jul 05 22:05:22 2017 +0200
@@ -644,23 +644,20 @@
      * <code>getProperties</code> operation, it may choose to permit the
      * {@link #getProperty(String)} operation.
      *
-     * @implNote In addition to the standard system properties, the {@code
-     * java} launcher may create the Java Virtual Machine with system
-     * properties that have the following keys:
+     * @implNote In addition to the standard system properties, the system
+     * properties may include the following keys:
      * <table summary="Shows property keys and associated values">
      * <tr><th>Key</th>
      *     <th>Description of Associated Value</th></tr>
      * <tr><td>{@code jdk.module.path}</td>
-     *     <td>Application module path</td></tr>
-     * <tr><td>{@code jdk.upgrade.module.path}</td>
+     *     <td>The application module path</td></tr>
+     * <tr><td>{@code jdk.module.upgrade.path}</td>
      *     <td>The upgrade module path</td></tr>
      * <tr><td>{@code jdk.module.main}</td>
      *     <td>The module name of the initial/main module</td></tr>
      * <tr><td>{@code jdk.module.main.class}</td>
      *     <td>The main class name of the initial module</td></tr>
      * </table>
-     * These properties may also be set by custom launchers that use the JNI
-     * invocation API to create the Java Virtual Machine.
      *
      * @return     the system properties
      * @exception  SecurityException  if a security manager exists and its
--- a/jdk/src/java.base/share/classes/java/lang/invoke/BoundMethodHandle.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/src/java.base/share/classes/java/lang/invoke/BoundMethodHandle.java	Wed Jul 05 22:05:22 2017 +0200
@@ -587,26 +587,7 @@
             return bmhClass;
         }
 
-        /**
-         * @implNote this method is used by GenerateBMHClassesPlugin to enable
-         * ahead-of-time generation of BMH classes at link time. It does
-         * added validation since this string may be user provided.
-         */
-        static Map.Entry<String, byte[]> generateConcreteBMHClassBytes(
-                final String types) {
-            for (char c : types.toCharArray()) {
-                if ("LIJFD".indexOf(c) < 0) {
-                    throw new IllegalArgumentException("All characters must "
-                            + "correspond to a basic field type: LIJFD");
-                }
-            }
-            String shortTypes = LambdaForm.shortenSignature(types);
-            final String className  = speciesInternalClassName(shortTypes);
-            return Map.entry(className,
-                    generateConcreteBMHClassBytes(shortTypes, types, className));
-        }
-
-        private static String speciesInternalClassName(String shortTypes) {
+        static String speciesInternalClassName(String shortTypes) {
             return SPECIES_PREFIX_PATH + shortTypes;
         }
 
@@ -865,7 +846,7 @@
         }
     }
 
-    private static final Lookup LOOKUP = Lookup.IMPL_LOOKUP;
+    static final Lookup LOOKUP = Lookup.IMPL_LOOKUP;
 
     /**
      * All subclasses must provide such a value describing their type signature.
--- a/jdk/src/java.base/share/classes/java/lang/invoke/DirectMethodHandle.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/src/java.base/share/classes/java/lang/invoke/DirectMethodHandle.java	Wed Jul 05 22:05:22 2017 +0200
@@ -186,7 +186,7 @@
         return mtype.form().setCachedLambdaForm(which, lform);
     }
 
-    private static LambdaForm makePreparedLambdaForm(MethodType mtype, int which) {
+    static LambdaForm makePreparedLambdaForm(MethodType mtype, int which) {
         boolean needsInit = (which == LF_INVSTATIC_INIT);
         boolean doesAlloc = (which == LF_NEWINVSPECIAL);
         String linkerName, lambdaName;
@@ -248,20 +248,6 @@
         return lform;
     }
 
-    /*
-     * NOTE: This method acts as an API hook for use by the
-     * GenerateJLIClassesPlugin to generate a class wrapping DirectMethodHandle
-     * methods for an array of method types.
-     */
-    static byte[] generateDMHClassBytes(String className, MethodType[] methodTypes, int[] types) {
-        LambdaForm[] forms = new LambdaForm[methodTypes.length];
-        for (int i = 0; i < forms.length; i++) {
-            forms[i] = makePreparedLambdaForm(methodTypes[i], types[i]);
-            methodTypes[i] = forms[i].methodType();
-        }
-        return InvokerBytecodeGenerator.generateCodeBytesForMultiple(className, forms, methodTypes);
-    }
-
     static Object findDirectMethodHandle(Name name) {
         if (name.function == NF_internalMemberName ||
             name.function == NF_internalMemberNameEnsureInit ||
@@ -273,7 +259,7 @@
     }
 
     private static void maybeCompile(LambdaForm lform, MemberName m) {
-        if (VerifyAccess.isSamePackage(m.getDeclaringClass(), MethodHandle.class))
+        if (lform.vmentry == null && VerifyAccess.isSamePackage(m.getDeclaringClass(), MethodHandle.class))
             // Help along bootstrapping...
             lform.compileToBytecode();
     }
@@ -515,7 +501,7 @@
     // Enumerate the different field kinds using Wrapper,
     // with an extra case added for checked references.
     private static final int
-            FT_LAST_WRAPPER    = Wrapper.values().length-1,
+            FT_LAST_WRAPPER    = Wrapper.COUNT-1,
             FT_UNCHECKED_REF   = Wrapper.OBJECT.ordinal(),
             FT_CHECKED_REF     = FT_LAST_WRAPPER+1,
             FT_LIMIT           = FT_LAST_WRAPPER+2;
@@ -576,25 +562,36 @@
         return lform;
     }
 
+    private static final Wrapper[] ALL_WRAPPERS = Wrapper.values();
+
     private static LambdaForm makePreparedFieldLambdaForm(byte formOp, boolean isVolatile, int ftypeKind) {
         boolean isGetter  = (formOp & 1) == (AF_GETFIELD & 1);
         boolean isStatic  = (formOp >= AF_GETSTATIC);
         boolean needsInit = (formOp >= AF_GETSTATIC_INIT);
         boolean needsCast = (ftypeKind == FT_CHECKED_REF);
-        Wrapper fw = (needsCast ? Wrapper.OBJECT : Wrapper.values()[ftypeKind]);
+        Wrapper fw = (needsCast ? Wrapper.OBJECT : ALL_WRAPPERS[ftypeKind]);
         Class<?> ft = fw.primitiveType();
         assert(ftypeKind(needsCast ? String.class : ft) == ftypeKind);
-        String tname  = fw.primitiveSimpleName();
-        String ctname = Character.toUpperCase(tname.charAt(0)) + tname.substring(1);
-        if (isVolatile)  ctname += "Volatile";
-        String getOrPut = (isGetter ? "get" : "put");
-        String linkerName = (getOrPut + ctname);  // getObject, putIntVolatile, etc.
+
+        // getObject, putIntVolatile, etc.
+        StringBuilder nameBuilder = new StringBuilder();
+        if (isGetter) {
+            nameBuilder.append("get");
+        } else {
+            nameBuilder.append("put");
+        }
+        nameBuilder.append(fw.primitiveSimpleName());
+        nameBuilder.setCharAt(3, Character.toUpperCase(nameBuilder.charAt(3)));
+        if (isVolatile) {
+            nameBuilder.append("Volatile");
+        }
+
         MethodType linkerType;
         if (isGetter)
             linkerType = MethodType.methodType(ft, Object.class, long.class);
         else
             linkerType = MethodType.methodType(void.class, Object.class, long.class, ft);
-        MemberName linker = new MemberName(Unsafe.class, linkerName, linkerType, REF_invokeVirtual);
+        MemberName linker = new MemberName(Unsafe.class, nameBuilder.toString(), linkerType, REF_invokeVirtual);
         try {
             linker = IMPL_NAMES.resolveOrFail(REF_invokeVirtual, linker, null, NoSuchMethodException.class);
         } catch (ReflectiveOperationException ex) {
@@ -649,11 +646,16 @@
         if (needsCast && isGetter)
             names[POST_CAST] = new Name(NF_checkCast, names[DMH_THIS], names[LINKER_CALL]);
         for (Name n : names)  assert(n != null);
-        String fieldOrStatic = (isStatic ? "Static" : "Field");
-        String lambdaName = (linkerName + fieldOrStatic);  // significant only for debugging
-        if (needsCast)  lambdaName += "Cast";
-        if (needsInit)  lambdaName += "Init";
-        return new LambdaForm(lambdaName, ARG_LIMIT, names, RESULT);
+        // add some detail to the lambdaForm debugname,
+        // significant only for debugging
+        if (isStatic) {
+            nameBuilder.append("Static");
+        } else {
+            nameBuilder.append("Field");
+        }
+        if (needsCast)  nameBuilder.append("Cast");
+        if (needsInit)  nameBuilder.append("Init");
+        return new LambdaForm(nameBuilder.toString(), ARG_LIMIT, names, RESULT);
     }
 
     /**
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/java.base/share/classes/java/lang/invoke/GenerateJLIClassesHelper.java	Wed Jul 05 22:05:22 2017 +0200
@@ -0,0 +1,85 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package java.lang.invoke;
+
+import java.util.Map;
+import jdk.internal.org.objectweb.asm.ClassWriter;
+import jdk.internal.org.objectweb.asm.Opcodes;
+
+/**
+ * Helper class to assist the GenerateJLIClassesPlugin to get access to
+ * generate classes ahead of time.
+ */
+class GenerateJLIClassesHelper {
+
+    static byte[] generateDMHClassBytes(String className,
+            MethodType[] methodTypes, int[] types) {
+        LambdaForm[] forms = new LambdaForm[methodTypes.length];
+        for (int i = 0; i < forms.length; i++) {
+            forms[i] = DirectMethodHandle.makePreparedLambdaForm(methodTypes[i],
+                                                                 types[i]);
+            methodTypes[i] = forms[i].methodType();
+        }
+        return generateCodeBytesForLFs(className, forms, methodTypes);
+    }
+
+    /*
+     * Generate customized code for a set of LambdaForms of specified types into
+     * a class with a specified name.
+     */
+    private static byte[] generateCodeBytesForLFs(String className,
+            LambdaForm[] forms, MethodType[] types) {
+        assert(forms.length == types.length);
+
+        ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS + ClassWriter.COMPUTE_FRAMES);
+        cw.visit(Opcodes.V1_8, Opcodes.ACC_PRIVATE + Opcodes.ACC_FINAL + Opcodes.ACC_SUPER,
+                className, null, InvokerBytecodeGenerator.INVOKER_SUPER_NAME, null);
+        cw.visitSource(className.substring(className.lastIndexOf('/') + 1), null);
+        for (int i = 0; i < forms.length; i++) {
+            InvokerBytecodeGenerator g
+                    = new InvokerBytecodeGenerator(className, forms[i], types[i]);
+            g.setClassWriter(cw);
+            g.addMethod();
+        }
+        return cw.toByteArray();
+    }
+
+    static Map.Entry<String, byte[]> generateConcreteBMHClassBytes(
+            final String types) {
+        for (char c : types.toCharArray()) {
+            if ("LIJFD".indexOf(c) < 0) {
+                throw new IllegalArgumentException("All characters must "
+                        + "correspond to a basic field type: LIJFD");
+            }
+        }
+        String shortTypes = LambdaForm.shortenSignature(types);
+        final String className =
+                BoundMethodHandle.Factory.speciesInternalClassName(shortTypes);
+        return Map.entry(className,
+                         BoundMethodHandle.Factory.generateConcreteBMHClassBytes(
+                                 shortTypes, types, className));
+    }
+}
--- a/jdk/src/java.base/share/classes/java/lang/invoke/InvokerBytecodeGenerator.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/src/java.base/share/classes/java/lang/invoke/InvokerBytecodeGenerator.java	Wed Jul 05 22:05:22 2017 +0200
@@ -40,8 +40,8 @@
 import java.io.IOException;
 import java.lang.reflect.Modifier;
 import java.util.Arrays;
+import java.util.ArrayList;
 import java.util.HashMap;
-import java.util.Map;
 import java.util.stream.Stream;
 
 import static java.lang.invoke.LambdaForm.*;
@@ -68,9 +68,10 @@
     private static final String LFN_SIG = "L" + LFN + ";";
     private static final String LL_SIG  = "(L" + OBJ + ";)L" + OBJ + ";";
     private static final String LLV_SIG = "(L" + OBJ + ";L" + OBJ + ";)V";
+    private static final String CLASS_PREFIX = LF + "$";
 
     /** Name of its super class*/
-    private static final String INVOKER_SUPER_NAME = OBJ;
+    static final String INVOKER_SUPER_NAME = OBJ;
 
     /** Name of new class */
     private final String className;
@@ -96,15 +97,15 @@
     /** Main constructor; other constructors delegate to this one. */
     private InvokerBytecodeGenerator(LambdaForm lambdaForm, int localsMapSize,
                                      String className, String invokerName, MethodType invokerType) {
-        if (invokerName.contains(".")) {
-            int p = invokerName.indexOf('.');
+        int p = invokerName.indexOf('.');
+        if (p > -1) {
             className = invokerName.substring(0, p);
-            invokerName = invokerName.substring(p+1);
+            invokerName = invokerName.substring(p + 1);
         }
         if (DUMP_CLASS_FILES) {
             className = makeDumpableClassName(className);
         }
-        this.className  = LF + "$" + className;
+        this.className  = CLASS_PREFIX + className;
         this.sourceFile = "LambdaForm$" + className;
         this.lambdaForm = lambdaForm;
         this.invokerName = invokerName;
@@ -124,7 +125,7 @@
     }
 
     /** For generating customized code for a single LambdaForm. */
-    private InvokerBytecodeGenerator(String className, LambdaForm form, MethodType invokerType) {
+    InvokerBytecodeGenerator(String className, LambdaForm form, MethodType invokerType) {
         this(form, form.names.length,
              className, form.debugName, invokerType);
         // Create an array to map name indexes to locals indexes.
@@ -201,38 +202,34 @@
 
     class CpPatch {
         final int index;
-        final String placeholder;
         final Object value;
-        CpPatch(int index, String placeholder, Object value) {
+        CpPatch(int index, Object value) {
             this.index = index;
-            this.placeholder = placeholder;
             this.value = value;
         }
         public String toString() {
-            return "CpPatch/index="+index+",placeholder="+placeholder+",value="+value;
+            return "CpPatch/index="+index+",value="+value;
         }
     }
 
-    Map<Object, CpPatch> cpPatches = new HashMap<>();
+    private final ArrayList<CpPatch> cpPatches = new ArrayList<>();
 
-    int cph = 0;  // for counting constant placeholders
+    private int cph = 0;  // for counting constant placeholders
 
     String constantPlaceholder(Object arg) {
         String cpPlaceholder = "CONSTANT_PLACEHOLDER_" + cph++;
-        if (DUMP_CLASS_FILES) cpPlaceholder += " <<" + debugString(arg) + ">>";  // debugging aid
-        if (cpPatches.containsKey(cpPlaceholder)) {
-            throw new InternalError("observed CP placeholder twice: " + cpPlaceholder);
-        }
+        if (DUMP_CLASS_FILES) cpPlaceholder += " <<" + debugString(arg) + ">>";
+        // TODO check if arg is already in the constant pool
         // insert placeholder in CP and remember the patch
-        int index = cw.newConst((Object) cpPlaceholder);  // TODO check if already in the constant pool
-        cpPatches.put(cpPlaceholder, new CpPatch(index, cpPlaceholder, arg));
+        int index = cw.newConst((Object) cpPlaceholder);
+        cpPatches.add(new CpPatch(index, arg));
         return cpPlaceholder;
     }
 
     Object[] cpPatches(byte[] classFile) {
         int size = getConstantPoolSize(classFile);
         Object[] res = new Object[size];
-        for (CpPatch p : cpPatches.values()) {
+        for (CpPatch p : cpPatches) {
             if (p.index >= size)
                 throw new InternalError("in cpool["+size+"]: "+p+"\n"+Arrays.toString(Arrays.copyOf(classFile, 20)));
             res[p.index] = p.value;
@@ -655,35 +652,11 @@
         return classFile;
     }
 
-    /*
-     * NOTE: This is used from GenerateJLIClassesPlugin via
-     * DirectMethodHandle::generateDMHClassBytes.
-     *
-     * Generate customized code for a set of LambdaForms of specified types into
-     * a class with a specified name.
-     */
-    static byte[] generateCodeBytesForMultiple(String className,
-            LambdaForm[] forms, MethodType[] types) {
-        assert(forms.length == types.length);
-
-        ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS + ClassWriter.COMPUTE_FRAMES);
-        cw.visit(Opcodes.V1_8, Opcodes.ACC_PRIVATE + Opcodes.ACC_FINAL + Opcodes.ACC_SUPER,
-                className, null, INVOKER_SUPER_NAME, null);
-        cw.visitSource(className.substring(className.lastIndexOf('/') + 1), null);
-        for (int i = 0; i < forms.length; i++) {
-            InvokerBytecodeGenerator g
-                    = new InvokerBytecodeGenerator(className, forms[i], types[i]);
-            g.setClassWriter(cw);
-            g.addMethod();
-        }
-        return cw.toByteArray();
-    }
-
-    private void setClassWriter(ClassWriter cw) {
+    void setClassWriter(ClassWriter cw) {
         this.cw = cw;
     }
 
-    private void addMethod() {
+    void addMethod() {
         methodPrologue();
 
         // Suppress this method in backtraces displayed to the user.
@@ -765,7 +738,7 @@
                     continue;
                 case IDENTITY:
                     assert(name.arguments.length == 1);
-                    emitPushArguments(name);
+                    emitPushArguments(name, 0);
                     continue;
                 case ZERO:
                     assert(name.arguments.length == 0);
@@ -819,7 +792,7 @@
         assert arrayOpcode == Opcodes.AALOAD || arrayOpcode == Opcodes.AASTORE || arrayOpcode == Opcodes.ARRAYLENGTH;
         Class<?> elementType = name.function.methodType().parameterType(0).getComponentType();
         assert elementType != null;
-        emitPushArguments(name);
+        emitPushArguments(name, 0);
         if (arrayOpcode != Opcodes.ARRAYLENGTH && elementType.isPrimitive()) {
             Wrapper w = Wrapper.forPrimitiveType(elementType);
             arrayOpcode = arrayInsnOpcode(arrayTypeCode(w), arrayOpcode);
@@ -848,7 +821,7 @@
         }
 
         // push arguments
-        emitPushArguments(name);
+        emitPushArguments(name, 0);
 
         // invocation
         MethodType type = name.function.methodType();
@@ -947,7 +920,7 @@
         assert(!(member.getDeclaringClass().isInterface() && refKind == REF_invokeVirtual));
 
         // push arguments
-        emitPushArguments(name);
+        emitPushArguments(name, 0);
 
         // invocation
         if (member.isMethod()) {
@@ -1468,13 +1441,10 @@
         }
     }
 
-    private void emitPushArguments(Name args) {
-        emitPushArguments(args, 0);
-    }
-
     private void emitPushArguments(Name args, int start) {
+        MethodType type = args.function.methodType();
         for (int i = start; i < args.arguments.length; i++) {
-            emitPushArgument(args, i);
+            emitPushArgument(type.parameterType(i), args.arguments[i]);
         }
     }
 
--- a/jdk/src/java.base/share/classes/java/lang/invoke/LambdaForm.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/src/java.base/share/classes/java/lang/invoke/LambdaForm.java	Wed Jul 05 22:05:22 2017 +0200
@@ -149,9 +149,9 @@
         static final int ARG_TYPE_LIMIT = ARG_TYPES.length;
         static final int TYPE_LIMIT = ALL_TYPES.length;
 
-        private final char btChar;
-        private final Class<?> btClass;
-        private final Wrapper btWrapper;
+        final char btChar;
+        final Class<?> btClass;
+        final Wrapper btWrapper;
 
         private BasicType(char btChar, Class<?> btClass, Wrapper wrapper) {
             this.btChar = btChar;
@@ -1366,10 +1366,11 @@
     }
 
     public static String basicTypeSignature(MethodType type) {
-        char[] sig = new char[type.parameterCount() + 2];
+        int params = type.parameterCount();
+        char[] sig = new char[params + 2];
         int sigp = 0;
-        for (Class<?> pt : type.parameterList()) {
-            sig[sigp++] = basicTypeChar(pt);
+        while (sigp < params) {
+            sig[sigp] = basicTypeChar(type.parameterType(sigp++));
         }
         sig[sigp++] = '_';
         sig[sigp++] = basicTypeChar(type.returnType());
@@ -1407,7 +1408,7 @@
 
     static final class Name {
         final BasicType type;
-        private short index;
+        @Stable short index;
         final NamedFunction function;
         final Object constraint;  // additional type information, if not null
         @Stable final Object[] arguments;
--- a/jdk/src/java.base/share/classes/java/lang/invoke/LambdaFormEditor.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/src/java.base/share/classes/java/lang/invoke/LambdaFormEditor.java	Wed Jul 05 22:05:22 2017 +0200
@@ -60,7 +60,7 @@
     }
 
     /** A description of a cached transform, possibly associated with the result of the transform.
-     *  The logical content is a sequence of byte values, starting with a Kind.ordinal value.
+     *  The logical content is a sequence of byte values, starting with a kind value.
      *  The sequence is unterminated, ending with an indefinite number of zero bytes.
      *  Sequences that are simple (short enough and with small enough values) pack into a 64-bit long.
      */
@@ -68,17 +68,22 @@
         final long packedBytes;
         final byte[] fullBytes;
 
-        private enum Kind {
-            NO_KIND,  // necessary because ordinal must be greater than zero
-            BIND_ARG, ADD_ARG, DUP_ARG,
-            SPREAD_ARGS,
-            FILTER_ARG, FILTER_RETURN, FILTER_RETURN_TO_ZERO,
-            COLLECT_ARGS, COLLECT_ARGS_TO_VOID, COLLECT_ARGS_TO_ARRAY,
-            FOLD_ARGS, FOLD_ARGS_TO_VOID,
-            PERMUTE_ARGS,
-            LOCAL_TYPES
-            //maybe add more for guard with test, catch exception, pointwise type conversions
-        }
+        // maybe add more for guard with test, catch exception, pointwise type conversions
+        private static final byte
+                BIND_ARG = 1,
+                ADD_ARG = 2,
+                DUP_ARG = 3,
+                SPREAD_ARGS = 4,
+                FILTER_ARG = 5,
+                FILTER_RETURN = 6,
+                FILTER_RETURN_TO_ZERO = 7,
+                COLLECT_ARGS = 8,
+                COLLECT_ARGS_TO_VOID = 9,
+                COLLECT_ARGS_TO_ARRAY = 10,
+                FOLD_ARGS = 11,
+                FOLD_ARGS_TO_VOID = 12,
+                PERMUTE_ARGS = 13,
+                LOCAL_TYPES = 14;
 
         private static final boolean STRESS_TEST = false; // turn on to disable most packing
         private static final int
@@ -131,20 +136,6 @@
             return bytes;
         }
 
-        private byte byteAt(int i) {
-            long pb = packedBytes;
-            if (pb == 0) {
-                if (i >= fullBytes.length)  return 0;
-                return fullBytes[i];
-            }
-            assert(fullBytes == null);
-            if (i > PACKED_BYTE_MAX_LENGTH)  return 0;
-            int pos = (i * PACKED_BYTE_SIZE);
-            return (byte)((pb >>> pos) & PACKED_BYTE_MASK);
-        }
-
-        Kind kind() { return Kind.values()[byteAt(0)]; }
-
         private Transform(long packedBytes, byte[] fullBytes, LambdaForm result) {
             super(result);
             this.packedBytes = packedBytes;
@@ -162,44 +153,39 @@
             assert((b & 0xFF) == b);  // incoming value must fit in *unsigned* byte
             return (byte)b;
         }
-        private static byte bval(Kind k) {
-            return bval(k.ordinal());
-        }
-        static Transform of(Kind k, int b1) {
+        static Transform of(byte k, int b1) {
             byte b0 = bval(k);
             if (inRange(b0 | b1))
                 return new Transform(packedBytes(b0, b1));
             else
                 return new Transform(fullBytes(b0, b1));
         }
-        static Transform of(Kind k, int b1, int b2) {
-            byte b0 = (byte) k.ordinal();
+        static Transform of(byte b0, int b1, int b2) {
             if (inRange(b0 | b1 | b2))
                 return new Transform(packedBytes(b0, b1, b2));
             else
                 return new Transform(fullBytes(b0, b1, b2));
         }
-        static Transform of(Kind k, int b1, int b2, int b3) {
-            byte b0 = (byte) k.ordinal();
+        static Transform of(byte b0, int b1, int b2, int b3) {
             if (inRange(b0 | b1 | b2 | b3))
                 return new Transform(packedBytes(b0, b1, b2, b3));
             else
                 return new Transform(fullBytes(b0, b1, b2, b3));
         }
         private static final byte[] NO_BYTES = {};
-        static Transform of(Kind k, int... b123) {
-            return ofBothArrays(k, b123, NO_BYTES);
+        static Transform of(byte kind, int... b123) {
+            return ofBothArrays(kind, b123, NO_BYTES);
         }
-        static Transform of(Kind k, int b1, byte[] b234) {
-            return ofBothArrays(k, new int[]{ b1 }, b234);
+        static Transform of(byte kind, int b1, byte[] b234) {
+            return ofBothArrays(kind, new int[]{ b1 }, b234);
         }
-        static Transform of(Kind k, int b1, int b2, byte[] b345) {
-            return ofBothArrays(k, new int[]{ b1, b2 }, b345);
+        static Transform of(byte kind, int b1, int b2, byte[] b345) {
+            return ofBothArrays(kind, new int[]{ b1, b2 }, b345);
         }
-        private static Transform ofBothArrays(Kind k, int[] b123, byte[] b456) {
+        private static Transform ofBothArrays(byte kind, int[] b123, byte[] b456) {
             byte[] fullBytes = new byte[1 + b123.length + b456.length];
             int i = 0;
-            fullBytes[i++] = bval(k);
+            fullBytes[i++] = bval(kind);
             for (int bv : b123) {
                 fullBytes[i++] = bval(bv);
             }
@@ -449,7 +435,7 @@
     // Each editing method can (potentially) cache the edited LF so that it can be reused later.
 
     LambdaForm bindArgumentForm(int pos) {
-        Transform key = Transform.of(Transform.Kind.BIND_ARG, pos);
+        Transform key = Transform.of(Transform.BIND_ARG, pos);
         LambdaForm form = getInCache(key);
         if (form != null) {
             assert(form.parameterConstraint(0) == newSpeciesData(lambdaForm.parameterType(pos)));
@@ -484,7 +470,7 @@
     }
 
     LambdaForm addArgumentForm(int pos, BasicType type) {
-        Transform key = Transform.of(Transform.Kind.ADD_ARG, pos, type.ordinal());
+        Transform key = Transform.of(Transform.ADD_ARG, pos, type.ordinal());
         LambdaForm form = getInCache(key);
         if (form != null) {
             assert(form.arity == lambdaForm.arity+1);
@@ -501,7 +487,7 @@
     }
 
     LambdaForm dupArgumentForm(int srcPos, int dstPos) {
-        Transform key = Transform.of(Transform.Kind.DUP_ARG, srcPos, dstPos);
+        Transform key = Transform.of(Transform.DUP_ARG, srcPos, dstPos);
         LambdaForm form = getInCache(key);
         if (form != null) {
             assert(form.arity == lambdaForm.arity-1);
@@ -530,7 +516,7 @@
                 elementTypeKey = TYPE_LIMIT + Wrapper.forPrimitiveType(elementType).ordinal();
             }
         }
-        Transform key = Transform.of(Transform.Kind.SPREAD_ARGS, pos, elementTypeKey, arrayLength);
+        Transform key = Transform.of(Transform.SPREAD_ARGS, pos, elementTypeKey, arrayLength);
         LambdaForm form = getInCache(key);
         if (form != null) {
             assert(form.arity == lambdaForm.arity - arrayLength + 1);
@@ -569,9 +555,9 @@
             return filterArgumentForm(pos, basicType(collectorType.parameterType(0)));
         }
         byte[] newTypes = BasicType.basicTypesOrd(collectorType.parameterArray());
-        Transform.Kind kind = (dropResult
-                ? Transform.Kind.COLLECT_ARGS_TO_VOID
-                : Transform.Kind.COLLECT_ARGS);
+        byte kind = (dropResult
+                ? Transform.COLLECT_ARGS_TO_VOID
+                : Transform.COLLECT_ARGS);
         if (dropResult && collectorArity == 0)  pos = 1;  // pure side effect
         Transform key = Transform.of(kind, pos, collectorArity, newTypes);
         LambdaForm form = getInCache(key);
@@ -598,7 +584,7 @@
             argTypeKey = TYPE_LIMIT + Wrapper.forPrimitiveType(elementType).ordinal();
         }
         assert(collectorType.parameterList().equals(Collections.nCopies(collectorArity, elementType)));
-        Transform.Kind kind = Transform.Kind.COLLECT_ARGS_TO_ARRAY;
+        byte kind = Transform.COLLECT_ARGS_TO_ARRAY;
         Transform key = Transform.of(kind, pos, collectorArity, argTypeKey);
         LambdaForm form = getInCache(key);
         if (form != null) {
@@ -634,7 +620,7 @@
     }
 
     LambdaForm filterArgumentForm(int pos, BasicType newType) {
-        Transform key = Transform.of(Transform.Kind.FILTER_ARG, pos, newType.ordinal());
+        Transform key = Transform.of(Transform.FILTER_ARG, pos, newType.ordinal());
         LambdaForm form = getInCache(key);
         if (form != null) {
             assert(form.arity == lambdaForm.arity);
@@ -710,7 +696,7 @@
     }
 
     LambdaForm filterReturnForm(BasicType newType, boolean constantZero) {
-        Transform.Kind kind = (constantZero ? Transform.Kind.FILTER_RETURN_TO_ZERO : Transform.Kind.FILTER_RETURN);
+        byte kind = (constantZero ? Transform.FILTER_RETURN_TO_ZERO : Transform.FILTER_RETURN);
         Transform key = Transform.of(kind, newType.ordinal());
         LambdaForm form = getInCache(key);
         if (form != null) {
@@ -762,11 +748,11 @@
 
     LambdaForm foldArgumentsForm(int foldPos, boolean dropResult, MethodType combinerType) {
         int combinerArity = combinerType.parameterCount();
-        Transform.Kind kind = (dropResult ? Transform.Kind.FOLD_ARGS_TO_VOID : Transform.Kind.FOLD_ARGS);
+        byte kind = (dropResult ? Transform.FOLD_ARGS_TO_VOID : Transform.FOLD_ARGS);
         Transform key = Transform.of(kind, foldPos, combinerArity);
         LambdaForm form = getInCache(key);
         if (form != null) {
-            assert(form.arity == lambdaForm.arity - (kind == Transform.Kind.FOLD_ARGS ? 1 : 0));
+            assert(form.arity == lambdaForm.arity - (kind == Transform.FOLD_ARGS ? 1 : 0));
             return form;
         }
         form = makeArgumentCombinationForm(foldPos, combinerType, true, dropResult);
@@ -786,7 +772,7 @@
         }
         assert(skip + reorder.length == lambdaForm.arity);
         if (nullPerm)  return lambdaForm;  // do not bother to cache
-        Transform key = Transform.of(Transform.Kind.PERMUTE_ARGS, reorder);
+        Transform key = Transform.of(Transform.PERMUTE_ARGS, reorder);
         LambdaForm form = getInCache(key);
         if (form != null) {
             assert(form.arity == skip+inTypes) : form;
@@ -855,7 +841,7 @@
         int[] desc = BasicType.basicTypeOrds(localTypes);
         desc = Arrays.copyOf(desc, desc.length + 1);
         desc[desc.length - 1] = pos;
-        Transform key = Transform.of(Transform.Kind.LOCAL_TYPES, desc);
+        Transform key = Transform.of(Transform.LOCAL_TYPES, desc);
         LambdaForm form = getInCache(key);
         if (form != null) {
             return form;
--- a/jdk/src/java.base/share/classes/java/lang/invoke/MemberName.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/src/java.base/share/classes/java/lang/invoke/MemberName.java	Wed Jul 05 22:05:22 2017 +0200
@@ -25,8 +25,6 @@
 
 package java.lang.invoke;
 
-import jdk.internal.misc.JavaLangInvokeAccess;
-import jdk.internal.misc.SharedSecrets;
 import sun.invoke.util.BytecodeDescriptor;
 import sun.invoke.util.VerifyAccess;
 
@@ -37,7 +35,6 @@
 import java.lang.reflect.Modifier;
 import java.lang.reflect.Module;
 import java.util.ArrayList;
-import java.util.Arrays;
 import java.util.Collections;
 import java.util.Iterator;
 import java.util.List;
@@ -81,7 +78,7 @@
     private int      flags;       // modifier bits; see reflect.Modifier
     //@Injected JVM_Method* vmtarget;
     //@Injected int         vmindex;
-    private Object   resolution;  // if null, this guy is resolved
+    Object   resolution;  // if null, this guy is resolved
 
     /** Return the declaring class of this member.
      *  In the case of a bare name and type, the declaring class will be null.
@@ -829,7 +826,7 @@
         return resolution == null;
     }
 
-    private void initResolved(boolean isResolved) {
+    void initResolved(boolean isResolved) {
         assert(this.resolution == null);  // not initialized yet!
         if (!isResolved)
             this.resolution = this;
@@ -1002,7 +999,9 @@
                     Collections.addAll(result, buf0);
                 }
             }
-            result.addAll(Arrays.asList(buf).subList(0, bufCount));
+            for (int i = 0; i < bufCount; i++) {
+                result.add(buf[i]);
+            }
             // Signature matching is not the same as type matching, since
             // one signature might correspond to several types.
             // So if matchType is a Class or MethodType, refilter the results.
@@ -1150,27 +1149,4 @@
             return buf;
         }
     }
-
-    static {
-        // StackFrameInfo stores Member and this provides the shared secrets
-        // for stack walker to access MemberName information.
-        SharedSecrets.setJavaLangInvokeAccess(new JavaLangInvokeAccess() {
-            @Override
-            public Object newMemberName() {
-                return new MemberName();
-            }
-
-            @Override
-            public String getName(Object mname) {
-                MemberName memberName = (MemberName)mname;
-                return memberName.getName();
-            }
-
-            @Override
-            public boolean isNative(Object mname) {
-                MemberName memberName = (MemberName)mname;
-                return memberName.isNative();
-            }
-        });
-    }
 }
--- a/jdk/src/java.base/share/classes/java/lang/invoke/MethodHandleImpl.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/src/java.base/share/classes/java/lang/invoke/MethodHandleImpl.java	Wed Jul 05 22:05:22 2017 +0200
@@ -25,6 +25,8 @@
 
 package java.lang.invoke;
 
+import jdk.internal.misc.JavaLangInvokeAccess;
+import jdk.internal.misc.SharedSecrets;
 import jdk.internal.org.objectweb.asm.AnnotationVisitor;
 import jdk.internal.org.objectweb.asm.ClassWriter;
 import jdk.internal.org.objectweb.asm.MethodVisitor;
@@ -38,12 +40,11 @@
 import sun.invoke.util.Wrapper;
 
 import java.lang.reflect.Array;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
 import java.util.Arrays;
 import java.util.Collections;
 import java.util.Iterator;
 import java.util.List;
+import java.util.Map;
 import java.util.function.Function;
 import java.util.stream.Stream;
 
@@ -57,19 +58,6 @@
  * @author jrose
  */
 /*non-public*/ abstract class MethodHandleImpl {
-    // Do not adjust this except for special platforms:
-    private static final int MAX_ARITY;
-    static {
-        final Object[] values = { 255 };
-        AccessController.doPrivileged(new PrivilegedAction<>() {
-            @Override
-            public Void run() {
-                values[0] = Integer.getInteger(MethodHandleImpl.class.getName()+".MAX_ARITY", 255);
-                return null;
-            }
-        });
-        MAX_ARITY = (Integer) values[0];
-    }
 
     /// Factory methods to create method handles:
 
@@ -649,7 +637,7 @@
         MethodType srcType = targetType                 // (a..., [b...])=>r
                 .dropParameterTypes(collectArgPos, collectArgPos+collectValCount);
         if (!retainOriginalArgs) {                      // (a..., b...)=>r
-            srcType = srcType.insertParameterTypes(collectArgPos, collectorType.parameterList());
+            srcType = srcType.insertParameterTypes(collectArgPos, collectorType.parameterArray());
         }
         // in  arglist: [0: ...keep1 | cpos: collect...  | cpos+cacount: keep2... ]
         // out arglist: [0: ...keep1 | cpos: collectVal? | cpos+cvcount: keep2... ]
@@ -1094,7 +1082,7 @@
         int arity = type.parameterCount();
         if (arity > 1) {
             MethodHandle mh = throwException(type.dropParameterTypes(1, arity));
-            mh = MethodHandles.dropArguments(mh, 1, type.parameterList().subList(1, arity));
+            mh = MethodHandles.dropArguments(mh, 1, Arrays.copyOfRange(type.parameterArray(), 1, arity));
             return mh;
         }
         return makePairwiseConvert(NF_throwException.resolvedHandle(), type, false, true);
@@ -1710,6 +1698,39 @@
         } catch (ReflectiveOperationException ex) {
             throw newInternalError(ex);
         }
+
+        SharedSecrets.setJavaLangInvokeAccess(new JavaLangInvokeAccess() {
+            @Override
+            public Object newMemberName() {
+                return new MemberName();
+            }
+
+            @Override
+            public String getName(Object mname) {
+                MemberName memberName = (MemberName)mname;
+                return memberName.getName();
+            }
+
+            @Override
+            public boolean isNative(Object mname) {
+                MemberName memberName = (MemberName)mname;
+                return memberName.isNative();
+            }
+
+            @Override
+            public byte[] generateDMHClassBytes(String className,
+            MethodType[] methodTypes, int[] types) {
+                return GenerateJLIClassesHelper
+                        .generateDMHClassBytes(className, methodTypes, types);
+            }
+
+            @Override
+            public Map.Entry<String, byte[]> generateConcreteBMHClassBytes(
+                    final String types) {
+                return GenerateJLIClassesHelper
+                        .generateConcreteBMHClassBytes(types);
+            }
+        });
     }
 
     /** Result unboxing: ValueConversions.unbox() OR ValueConversions.identity() OR ValueConversions.ignore(). */
--- a/jdk/src/java.base/share/classes/java/lang/invoke/MethodHandleStatics.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/src/java.base/share/classes/java/lang/invoke/MethodHandleStatics.java	Wed Jul 05 22:05:22 2017 +0200
@@ -53,6 +53,7 @@
     static final boolean PROFILE_GWT;
     static final int CUSTOMIZE_THRESHOLD;
     static final boolean VAR_HANDLE_GUARDS;
+    static final int MAX_ARITY;
 
     static {
         Properties props = GetPropertyAction.privilegedGetProperties();
@@ -79,6 +80,10 @@
         VAR_HANDLE_GUARDS = Boolean.parseBoolean(
                 props.getProperty("java.lang.invoke.VarHandle.VAR_HANDLE_GUARDS", "true"));
 
+        // Do not adjust this except for special platforms:
+        MAX_ARITY = Integer.parseInt(
+                props.getProperty("java.lang.invoke.MethodHandleImpl.MAX_ARITY", "255"));
+
         if (CUSTOMIZE_THRESHOLD < -1 || CUSTOMIZE_THRESHOLD > 127) {
             throw newInternalError("CUSTOMIZE_THRESHOLD should be in [-1...127] range");
         }
--- a/jdk/src/java.base/share/classes/java/lang/invoke/MethodHandles.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/src/java.base/share/classes/java/lang/invoke/MethodHandles.java	Wed Jul 05 22:05:22 2017 +0200
@@ -77,7 +77,7 @@
 
     private MethodHandles() { }  // do not instantiate
 
-    private static final MemberName.Factory IMPL_NAMES = MemberName.getFactory();
+    static final MemberName.Factory IMPL_NAMES = MemberName.getFactory();
 
     // See IMPL_LOOKUP below.
 
@@ -3115,7 +3115,7 @@
         return dropArguments(zero(type.returnType()), 0, type.parameterList());
     }
 
-    private static final MethodHandle[] IDENTITY_MHS = new MethodHandle[Wrapper.values().length];
+    private static final MethodHandle[] IDENTITY_MHS = new MethodHandle[Wrapper.COUNT];
     private static MethodHandle makeIdentity(Class<?> ptype) {
         MethodType mtype = methodType(ptype, ptype);
         LambdaForm lform = LambdaForm.identityForm(BasicType.basicType(ptype));
@@ -3133,7 +3133,7 @@
         assert(btw == Wrapper.OBJECT);
         return makeZero(rtype);
     }
-    private static final MethodHandle[] ZERO_MHS = new MethodHandle[Wrapper.values().length];
+    private static final MethodHandle[] ZERO_MHS = new MethodHandle[Wrapper.COUNT];
     private static MethodHandle makeZero(Class<?> rtype) {
         MethodType mtype = methodType(rtype);
         LambdaForm lform = LambdaForm.zeroForm(BasicType.basicType(rtype));
@@ -3268,12 +3268,11 @@
      */
     public static
     MethodHandle dropArguments(MethodHandle target, int pos, List<Class<?>> valueTypes) {
-        return dropArguments0(target, pos, copyTypes(valueTypes));
+        return dropArguments0(target, pos, copyTypes(valueTypes.toArray()));
     }
 
-    private static List<Class<?>> copyTypes(List<Class<?>> types) {
-        Object[] a = types.toArray();
-        return Arrays.asList(Arrays.copyOf(a, a.length, Class[].class));
+    private static List<Class<?>> copyTypes(Object[] array) {
+        return Arrays.asList(Arrays.copyOf(array, array.length, Class[].class));
     }
 
     private static
@@ -3352,13 +3351,13 @@
      */
     public static
     MethodHandle dropArguments(MethodHandle target, int pos, Class<?>... valueTypes) {
-        return dropArguments(target, pos, Arrays.asList(valueTypes));
+        return dropArguments0(target, pos, copyTypes(valueTypes));
     }
 
     // private version which allows caller some freedom with error handling
     private static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos,
                                       boolean nullOnFailure) {
-        newTypes = copyTypes(newTypes);
+        newTypes = copyTypes(newTypes.toArray());
         List<Class<?>> oldTypes = target.type().parameterList();
         int match = oldTypes.size();
         if (skip != 0) {
@@ -3900,10 +3899,14 @@
         int foldVals = rtype == void.class ? 0 : 1;
         int afterInsertPos = foldPos + foldVals;
         boolean ok = (targetType.parameterCount() >= afterInsertPos + foldArgs);
-        if (ok && !(combinerType.parameterList()
-                    .equals(targetType.parameterList().subList(afterInsertPos,
-                                                               afterInsertPos + foldArgs))))
-            ok = false;
+        if (ok) {
+            for (int i = 0; i < foldArgs; i++) {
+                if (combinerType.parameterType(i) != targetType.parameterType(i + afterInsertPos)) {
+                    ok = false;
+                    break;
+                }
+            }
+        }
         if (ok && foldVals != 0 && combinerType.returnType() != targetType.parameterType(foldPos))
             ok = false;
         if (!ok)
--- a/jdk/src/java.base/share/classes/java/lang/invoke/MethodType.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/src/java.base/share/classes/java/lang/invoke/MethodType.java	Wed Jul 05 22:05:22 2017 +0200
@@ -539,10 +539,10 @@
             return res;
         } else {
             // insert after (if need be), then before
-            if (pos < parameterList().size() - 1) {
-                res = res.insertParameterTypes(arrayLength, parameterList().subList(pos + 1, parameterList().size()));
+            if (pos < ptypes.length - 1) {
+                res = res.insertParameterTypes(arrayLength, Arrays.copyOfRange(ptypes, pos + 1, ptypes.length));
             }
-            return res.insertParameterTypes(0, parameterList().subList(0, pos));
+            return res.insertParameterTypes(0, Arrays.copyOf(ptypes, pos));
         }
     }
 
--- a/jdk/src/java.base/share/classes/java/lang/invoke/StringConcatFactory.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/src/java.base/share/classes/java/lang/invoke/StringConcatFactory.java	Wed Jul 05 22:05:22 2017 +0200
@@ -281,12 +281,11 @@
                     if (c == TAG_CONST) {
                         Object cnst = constants[constC++];
                         el.add(new RecipeElement(cnst));
-                    }
-                    if (c == TAG_ARG) {
+                    } else if (c == TAG_ARG) {
                         el.add(new RecipeElement(argC++));
                     }
                 } else {
-                    // Not a special characters, this is a constant embedded into
+                    // Not a special character, this is a constant embedded into
                     // the recipe itself.
                     acc.append(c);
                 }
@@ -322,31 +321,31 @@
     private static final class RecipeElement {
         private final Object value;
         private final int argPos;
-        private final Tag tag;
+        private final char tag;
 
         public RecipeElement(Object cnst) {
             this.value = Objects.requireNonNull(cnst);
             this.argPos = -1;
-            this.tag = Tag.CONST;
+            this.tag = TAG_CONST;
         }
 
         public RecipeElement(int arg) {
             this.value = null;
             this.argPos = arg;
-            this.tag = Tag.ARG;
+            this.tag = TAG_ARG;
         }
 
         public Object getValue() {
-            assert (tag == Tag.CONST);
+            assert (tag == TAG_CONST);
             return value;
         }
 
         public int getArgPos() {
-            assert (tag == Tag.ARG);
+            assert (tag == TAG_ARG);
             return argPos;
         }
 
-        public Tag getTag() {
+        public char getTag() {
             return tag;
         }
 
@@ -357,22 +356,18 @@
 
             RecipeElement that = (RecipeElement) o;
 
-            if (tag != that.tag) return false;
-            if (tag == Tag.CONST && (!value.equals(that.value))) return false;
-            if (tag == Tag.ARG && (argPos != that.argPos)) return false;
+            if (this.tag != that.tag) return false;
+            if (this.tag == TAG_CONST && (!value.equals(that.value))) return false;
+            if (this.tag == TAG_ARG && (argPos != that.argPos)) return false;
             return true;
         }
 
         @Override
         public int hashCode() {
-            return tag.hashCode();
+            return (int)tag;
         }
     }
 
-    private enum Tag {
-        CONST, ARG
-    }
-
     /**
      * Facilitates the creation of optimized String concatenation methods, that
      * can be used to efficiently concatenate a known number of arguments of
@@ -649,19 +644,20 @@
      * @return argument types the strategy is going to use
      */
     private static MethodType adaptType(MethodType args) {
-        Class<?>[] ptypes = args.parameterArray();
-        boolean changed = false;
-        for (int i = 0; i < ptypes.length; i++) {
-            Class<?> ptype = ptypes[i];
+        Class<?>[] ptypes = null;
+        for (int i = 0; i < args.parameterCount(); i++) {
+            Class<?> ptype = args.parameterType(i);
             if (!ptype.isPrimitive() &&
                     ptype != String.class &&
                     ptype != Object.class) { // truncate to Object
+                if (ptypes == null) {
+                    ptypes = args.parameterArray();
+                }
                 ptypes[i] = Object.class;
-                changed = true;
             }
             // else other primitives or String or Object (unchanged)
         }
-        return changed
+        return (ptypes != null)
                 ? MethodType.methodType(args.returnType(), ptypes)
                 : args;
     }
@@ -881,11 +877,10 @@
                 int off = 0;
                 for (RecipeElement el : recipe.getElements()) {
                     switch (el.getTag()) {
-                        case CONST: {
+                        case TAG_CONST:
                             // Guaranteed non-null, no null check required.
                             break;
-                        }
-                        case ARG: {
+                        case TAG_ARG:
                             // Null-checks are needed only for String arguments, and when a previous stage
                             // did not do implicit null-checks. If a String is null, we eagerly replace it
                             // with "null" constant. Note, we omit Objects here, because we don't call
@@ -902,7 +897,6 @@
                             }
                             off += getParameterSize(cl);
                             break;
-                        }
                         default:
                             throw new StringConcatException("Unhandled tag: " + el.getTag());
                     }
@@ -926,12 +920,11 @@
 
                 for (RecipeElement el : recipe.getElements()) {
                     switch (el.getTag()) {
-                        case CONST: {
+                        case TAG_CONST:
                             Object cnst = el.getValue();
                             len += cnst.toString().length();
                             break;
-                        }
-                        case ARG: {
+                        case TAG_ARG:
                             /*
                                 If an argument is String, then we can call .length() on it. Sized/Exact modes have
                                 converted arguments for us. If an argument is primitive, we can provide a guess
@@ -953,7 +946,6 @@
                             }
                             off += getParameterSize(cl);
                             break;
-                        }
                         default:
                             throw new StringConcatException("Unhandled tag: " + el.getTag());
                     }
@@ -988,22 +980,21 @@
                 for (RecipeElement el : recipe.getElements()) {
                     String desc;
                     switch (el.getTag()) {
-                        case CONST: {
+                        case TAG_CONST:
                             Object cnst = el.getValue();
                             mv.visitLdcInsn(cnst);
                             desc = getSBAppendDesc(cnst.getClass());
                             break;
-                        }
-                        case ARG: {
+                        case TAG_ARG:
                             Class<?> cl = arr[el.getArgPos()];
                             mv.visitVarInsn(getLoadOpcode(cl), off);
                             off += getParameterSize(cl);
                             desc = getSBAppendDesc(cl);
                             break;
-                        }
                         default:
                             throw new StringConcatException("Unhandled tag: " + el.getTag());
                     }
+
                     mv.visitMethodInsn(
                             INVOKEVIRTUAL,
                             "java/lang/StringBuilder",
@@ -1271,7 +1262,6 @@
                 }
             }
 
-            List<Class<?>> ptypesList = Arrays.asList(ptypes);
             MethodHandle[] lengthers = new MethodHandle[pc];
 
             // Figure out lengths: constants' lengths can be deduced on the spot.
@@ -1280,14 +1270,13 @@
             int initial = 0;
             for (RecipeElement el : recipe.getElements()) {
                 switch (el.getTag()) {
-                    case CONST: {
+                    case TAG_CONST:
                         Object cnst = el.getValue();
                         initial += cnst.toString().length();
                         break;
-                    }
-                    case ARG: {
+                    case TAG_ARG:
                         final int i = el.getArgPos();
-                        Class<?> type = ptypesList.get(i);
+                        Class<?> type = ptypes[i];
                         if (type.isPrimitive()) {
                             MethodHandle est = MethodHandles.constant(int.class, estimateSize(type));
                             est = MethodHandles.dropArguments(est, 0, type);
@@ -1296,14 +1285,13 @@
                             lengthers[i] = STRING_LENGTH;
                         }
                         break;
-                    }
                     default:
                         throw new StringConcatException("Unhandled tag: " + el.getTag());
                 }
             }
 
             // Create (StringBuilder, <args>) shape for appending:
-            MethodHandle builder = MethodHandles.dropArguments(MethodHandles.identity(StringBuilder.class), 1, ptypesList);
+            MethodHandle builder = MethodHandles.dropArguments(MethodHandles.identity(StringBuilder.class), 1, ptypes);
 
             // Compose append calls. This is done in reverse because the application order is
             // reverse as well.
@@ -1312,23 +1300,21 @@
                 RecipeElement el = elements.get(i);
                 MethodHandle appender;
                 switch (el.getTag()) {
-                    case CONST: {
+                    case TAG_CONST:
                         Object constant = el.getValue();
                         MethodHandle mh = appender(adaptToStringBuilder(constant.getClass()));
                         appender = MethodHandles.insertArguments(mh, 1, constant);
                         break;
-                    }
-                    case ARG: {
+                    case TAG_ARG:
                         int ac = el.getArgPos();
-                        appender = appender(ptypesList.get(ac));
+                        appender = appender(ptypes[ac]);
 
                         // Insert dummy arguments to match the prefix in the signature.
                         // The actual appender argument will be the ac-ith argument.
                         if (ac != 0) {
-                            appender = MethodHandles.dropArguments(appender, 1, ptypesList.subList(0, ac));
+                            appender = MethodHandles.dropArguments(appender, 1, Arrays.copyOf(ptypes, ac));
                         }
                         break;
-                    }
                     default:
                         throw new StringConcatException("Unhandled tag: " + el.getTag());
                 }
@@ -1500,7 +1486,6 @@
                     ptypes[i] = filter.type().returnType();
                 }
             }
-            List<Class<?>> ptypesList = Arrays.asList(ptypes);
 
             // Start building the combinator tree. The tree "starts" with (<parameters>)String, and "finishes"
             // with the (int, byte[], byte)String in String helper. The combinators are assembled bottom-up,
@@ -1522,16 +1507,14 @@
             for (RecipeElement el : recipe.getElements()) {
                 MethodHandle prepender;
                 switch (el.getTag()) {
-                    case CONST: {
+                    case TAG_CONST:
                         Object cnst = el.getValue();
                         prepender = MethodHandles.insertArguments(prepender(cnst.getClass()), 3, cnst);
                         break;
-                    }
-                    case ARG: {
+                    case TAG_ARG:
                         int pos = el.getArgPos();
-                        prepender = selectArgument(prepender(ptypesList.get(pos)), 3, ptypesList, pos);
+                        prepender = selectArgument(prepender(ptypes[pos]), 3, ptypes, pos);
                         break;
-                    }
                     default:
                         throw new StringConcatException("Unhandled tag: " + el.getTag());
                 }
@@ -1554,7 +1537,7 @@
             }
 
             // Fold in byte[] instantiation at argument 0.
-            MethodHandle combiner = MethodHandles.dropArguments(NEW_ARRAY, 2, ptypesList);
+            MethodHandle combiner = MethodHandles.dropArguments(NEW_ARRAY, 2, ptypes);
             mh = MethodHandles.foldArguments(mh, combiner);
 
             // Start combining length and coder mixers.
@@ -1574,22 +1557,21 @@
             int initialLen = 0;    // initial length, in characters
             for (RecipeElement el : recipe.getElements()) {
                 switch (el.getTag()) {
-                    case CONST: {
+                    case TAG_CONST:
                         Object constant = el.getValue();
                         String s = constant.toString();
                         initialCoder = (byte) coderMixer(String.class).invoke(initialCoder, s);
                         initialLen += s.length();
                         break;
-                    }
-                    case ARG: {
+                    case TAG_ARG:
                         int ac = el.getArgPos();
 
-                        Class<?> argClass = ptypesList.get(ac);
-                        MethodHandle lm = selectArgument(lengthMixer(argClass), 1, ptypesList, ac);
+                        Class<?> argClass = ptypes[ac];
+                        MethodHandle lm = selectArgument(lengthMixer(argClass), 1, ptypes, ac);
                         lm = MethodHandles.dropArguments(lm, 0, byte.class); // (*)
                         lm = MethodHandles.dropArguments(lm, 2, byte.class);
 
-                        MethodHandle cm = selectArgument(coderMixer(argClass),  1, ptypesList, ac);
+                        MethodHandle cm = selectArgument(coderMixer(argClass),  1, ptypes, ac);
                         cm = MethodHandles.dropArguments(cm, 0, int.class);  // (**)
 
                         // Read this bottom up:
@@ -1607,7 +1589,6 @@
 
                         // 1. The mh shape here is ("old-index", "old-coder", <args>)
                         break;
-                    }
                     default:
                         throw new StringConcatException("Unhandled tag: " + el.getTag());
                 }
@@ -1636,14 +1617,14 @@
         }
 
         // Adapts: (...prefix..., parameter[pos])R -> (...prefix..., ...parameters...)R
-        private static MethodHandle selectArgument(MethodHandle mh, int prefix, List<Class<?>> ptypes, int pos) {
+        private static MethodHandle selectArgument(MethodHandle mh, int prefix, Class<?>[] ptypes, int pos) {
             if (pos == 0) {
-                return MethodHandles.dropArguments(mh, prefix + 1, ptypes.subList(1, ptypes.size()));
-            } else if (pos == ptypes.size() - 1) {
-                return MethodHandles.dropArguments(mh, prefix, ptypes.subList(0, ptypes.size() - 1));
+                return MethodHandles.dropArguments(mh, prefix + 1, Arrays.copyOfRange(ptypes, 1, ptypes.length));
+            } else if (pos == ptypes.length - 1) {
+                return MethodHandles.dropArguments(mh, prefix, Arrays.copyOf(ptypes, ptypes.length - 1));
             } else { // 0 < pos < ptypes.size() - 1
-                MethodHandle t = MethodHandles.dropArguments(mh, prefix, ptypes.subList(0, pos));
-                return MethodHandles.dropArguments(t, prefix + 1 + pos, ptypes.subList(pos + 1, ptypes.size()));
+                MethodHandle t = MethodHandles.dropArguments(mh, prefix, Arrays.copyOf(ptypes, pos));
+                return MethodHandles.dropArguments(t, prefix + 1 + pos, Arrays.copyOfRange(ptypes, pos + 1, ptypes.length));
             }
         }
 
@@ -1702,8 +1683,8 @@
         private static final ConcurrentMap<Class<?>, MethodHandle> PREPENDERS;
         private static final ConcurrentMap<Class<?>, MethodHandle> LENGTH_MIXERS;
         private static final ConcurrentMap<Class<?>, MethodHandle> CODER_MIXERS;
-        private static final Class<?> STRING_HELPER;
         private static final byte INITIAL_CODER;
+        static final Class<?> STRING_HELPER;
 
         static {
             try {
@@ -1805,7 +1786,7 @@
 
     /* ------------------------------- Common utilities ------------------------------------ */
 
-    private static MethodHandle lookupStatic(Lookup lookup, Class<?> refc, String name, Class<?> rtype, Class<?>... ptypes) {
+    static MethodHandle lookupStatic(Lookup lookup, Class<?> refc, String name, Class<?> rtype, Class<?>... ptypes) {
         try {
             return lookup.findStatic(refc, name, MethodType.methodType(rtype, ptypes));
         } catch (NoSuchMethodException | IllegalAccessException e) {
@@ -1813,7 +1794,7 @@
         }
     }
 
-    private static MethodHandle lookupVirtual(Lookup lookup, Class<?> refc, String name, Class<?> rtype, Class<?>... ptypes) {
+    static MethodHandle lookupVirtual(Lookup lookup, Class<?> refc, String name, Class<?> rtype, Class<?>... ptypes) {
         try {
             return lookup.findVirtual(refc, name, MethodType.methodType(rtype, ptypes));
         } catch (NoSuchMethodException | IllegalAccessException e) {
@@ -1821,7 +1802,7 @@
         }
     }
 
-    private static MethodHandle lookupConstructor(Lookup lookup, Class<?> refc, Class<?> ptypes) {
+    static MethodHandle lookupConstructor(Lookup lookup, Class<?> refc, Class<?> ptypes) {
         try {
             return lookup.findConstructor(refc, MethodType.methodType(void.class, ptypes));
         } catch (NoSuchMethodException | IllegalAccessException e) {
@@ -1829,7 +1810,7 @@
         }
     }
 
-    private static int estimateSize(Class<?> cl) {
+    static int estimateSize(Class<?> cl) {
         if (cl == Integer.TYPE) {
             return 11; // "-2147483648"
         } else if (cl == Boolean.TYPE) {
@@ -1851,7 +1832,7 @@
         }
     }
 
-    private static Class<?> adaptToStringBuilder(Class<?> c) {
+    static Class<?> adaptToStringBuilder(Class<?> c) {
         if (c.isPrimitive()) {
             if (c == Byte.TYPE || c == Short.TYPE) {
                 return int.class;
--- a/jdk/src/java.base/share/classes/java/lang/invoke/TypeConvertingMethodAdapter.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/src/java.base/share/classes/java/lang/invoke/TypeConvertingMethodAdapter.java	Wed Jul 05 22:05:22 2017 +0200
@@ -38,7 +38,7 @@
         super(Opcodes.ASM5, mv);
     }
 
-    private static final int NUM_WRAPPERS = Wrapper.values().length;
+    private static final int NUM_WRAPPERS = Wrapper.COUNT;
 
     private static final String NAME_OBJECT = "java/lang/Object";
     private static final String WRAPPER_PREFIX = "Ljava/lang/";
--- a/jdk/src/java.base/share/classes/java/lang/invoke/VarForm.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/src/java.base/share/classes/java/lang/invoke/VarForm.java	Wed Jul 05 22:05:22 2017 +0200
@@ -31,7 +31,6 @@
 import java.lang.reflect.Method;
 import java.lang.reflect.Modifier;
 import java.util.ArrayList;
-import java.util.Arrays;
 import java.util.List;
 
 /**
@@ -54,7 +53,8 @@
         List<Class<?>> l = new ArrayList<>();
         if (receiver != null)
             l.add(receiver);
-        l.addAll(Arrays.asList(intermediate));
+        for (Class<?> c : intermediate)
+            l.add(c);
 
         // (Receiver, <Intermediates>)Value
         methodType_table[VarHandle.AccessType.GET.ordinal()] =
--- a/jdk/src/java.base/share/classes/java/lang/invoke/VarHandle.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/src/java.base/share/classes/java/lang/invoke/VarHandle.java	Wed Jul 05 22:05:22 2017 +0200
@@ -1057,57 +1057,11 @@
     Object addAndGet(Object... args);
 
     enum AccessType {
-        GET(Object.class) {
-            @Override
-            MethodType accessModeType(Class<?> receiver, Class<?> value,
-                                      Class<?>... intermediate) {
-                Class<?>[] ps =  allocateParameters(0, receiver, intermediate);
-                fillParameters(ps, receiver, intermediate);
-                return MethodType.methodType(value, ps);
-            }
-        },
-        SET(void.class) {
-            @Override
-            MethodType accessModeType(Class<?> receiver, Class<?> value,
-                                      Class<?>... intermediate) {
-                Class<?>[] ps =  allocateParameters(1, receiver, intermediate);
-                int i = fillParameters(ps, receiver, intermediate);
-                ps[i] = value;
-                return MethodType.methodType(void.class, ps);
-            }
-        },
-        COMPARE_AND_SWAP(boolean.class) {
-            @Override
-            MethodType accessModeType(Class<?> receiver, Class<?> value,
-                                      Class<?>... intermediate) {
-                Class<?>[] ps =  allocateParameters(2, receiver, intermediate);
-                int i = fillParameters(ps, receiver, intermediate);
-                ps[i++] = value;
-                ps[i] = value;
-                return MethodType.methodType(boolean.class, ps);
-            }
-        },
-        COMPARE_AND_EXCHANGE(Object.class) {
-            @Override
-            MethodType accessModeType(Class<?> receiver, Class<?> value,
-                                      Class<?>... intermediate) {
-                Class<?>[] ps =  allocateParameters(2, receiver, intermediate);
-                int i = fillParameters(ps, receiver, intermediate);
-                ps[i++] = value;
-                ps[i] = value;
-                return MethodType.methodType(value, ps);
-            }
-        },
-        GET_AND_UPDATE(Object.class) {
-            @Override
-            MethodType accessModeType(Class<?> receiver, Class<?> value,
-                                      Class<?>... intermediate) {
-                Class<?>[] ps =  allocateParameters(1, receiver, intermediate);
-                int i = fillParameters(ps, receiver, intermediate);
-                ps[i] = value;
-                return MethodType.methodType(value, ps);
-            }
-        };
+        GET(Object.class),
+        SET(void.class),
+        COMPARE_AND_SWAP(boolean.class),
+        COMPARE_AND_EXCHANGE(Object.class),
+        GET_AND_UPDATE(Object.class);
 
         final Class<?> returnType;
         final boolean isMonomorphicInReturnType;
@@ -1117,8 +1071,41 @@
             isMonomorphicInReturnType = returnType != Object.class;
         }
 
-        abstract MethodType accessModeType(Class<?> receiver, Class<?> value,
-                                           Class<?>... intermediate);
+        MethodType accessModeType(Class<?> receiver, Class<?> value,
+                                  Class<?>... intermediate) {
+            Class<?>[] ps;
+            int i;
+            switch (this) {
+                case GET:
+                    ps = allocateParameters(0, receiver, intermediate);
+                    fillParameters(ps, receiver, intermediate);
+                    return MethodType.methodType(value, ps);
+                case SET:
+                    ps = allocateParameters(1, receiver, intermediate);
+                    i = fillParameters(ps, receiver, intermediate);
+                    ps[i] = value;
+                    return MethodType.methodType(void.class, ps);
+                case COMPARE_AND_SWAP:
+                    ps = allocateParameters(2, receiver, intermediate);
+                    i = fillParameters(ps, receiver, intermediate);
+                    ps[i++] = value;
+                    ps[i] = value;
+                    return MethodType.methodType(boolean.class, ps);
+                case COMPARE_AND_EXCHANGE:
+                    ps = allocateParameters(2, receiver, intermediate);
+                    i = fillParameters(ps, receiver, intermediate);
+                    ps[i++] = value;
+                    ps[i] = value;
+                    return MethodType.methodType(value, ps);
+                case GET_AND_UPDATE:
+                    ps = allocateParameters(1, receiver, intermediate);
+                    i = fillParameters(ps, receiver, intermediate);
+                    ps[i] = value;
+                    return MethodType.methodType(value, ps);
+                default:
+                    throw new InternalError("Unknown AccessType");
+            }
+        }
 
         private static Class<?>[] allocateParameters(int values,
                                                      Class<?> receiver, Class<?>... intermediate) {
--- a/jdk/src/java.base/share/classes/java/lang/module/ModuleReference.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/src/java.base/share/classes/java/lang/module/ModuleReference.java	Wed Jul 05 22:05:22 2017 +0200
@@ -169,7 +169,7 @@
 
 
     /**
-     * Returns {@code true} if this module has been patched via -Xpatch.
+     * Returns {@code true} if this module has been patched via --patch-module.
      */
     boolean isPatched() {
         return patched;
--- a/jdk/src/java.base/share/classes/java/lang/module/ModuleReferences.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/src/java.base/share/classes/java/lang/module/ModuleReferences.java	Wed Jul 05 22:05:22 2017 +0200
@@ -68,7 +68,7 @@
 
     /**
      * Creates a ModuleReference to a module or to patched module when
-     * creating modules for the boot Layer and -Xpatch is specified.
+     * creating modules for the boot Layer and --patch-module is specified.
      */
     private static ModuleReference newModule(ModuleDescriptor md,
                                              URI uri,
--- a/jdk/src/java.base/share/classes/java/lang/module/SystemModuleFinder.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/src/java.base/share/classes/java/lang/module/SystemModuleFinder.java	Wed Jul 05 22:05:22 2017 +0200
@@ -178,7 +178,7 @@
         ModuleReference mref =
             new ModuleReference(md, uri, readerSupplier, hash);
 
-        // may need a reference to a patched module if -Xpatch specified
+        // may need a reference to a patched module if --patch-module specified
         mref = ModulePatcher.interposeIfNeeded(mref);
 
         return mref;
--- a/jdk/src/java.base/share/classes/java/util/concurrent/atomic/AtomicBoolean.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/src/java.base/share/classes/java/util/concurrent/atomic/AtomicBoolean.java	Wed Jul 05 22:05:22 2017 +0200
@@ -147,11 +147,7 @@
      * @return the previous value
      */
     public final boolean getAndSet(boolean newValue) {
-        boolean prev;
-        do {
-            prev = get();
-        } while (!compareAndSet(prev, newValue));
-        return prev;
+        return (int)VALUE.getAndSet(this, (newValue ? 1 : 0)) != 0;
     }
 
     /**
--- a/jdk/src/java.base/share/classes/java/util/concurrent/locks/StampedLock.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/src/java.base/share/classes/java/util/concurrent/locks/StampedLock.java	Wed Jul 05 22:05:22 2017 +0200
@@ -263,6 +263,47 @@
      * is theoretically possible, so we additionally add a
      * storeStoreFence after lock acquisition CAS.
      *
+     * ----------------------------------------------------------------
+     * Here's an informal proof that plain reads by _successful_
+     * readers see plain writes from preceding but not following
+     * writers (following Boehm and the C++ standard [atomics.fences]):
+     *
+     * Because of the total synchronization order of accesses to
+     * volatile long state containing the sequence number, writers and
+     * _successful_ readers can be globally sequenced.
+     *
+     * int x, y;
+     *
+     * Writer 1:
+     * inc sequence (odd - "locked")
+     * storeStoreFence();
+     * x = 1; y = 2;
+     * inc sequence (even - "unlocked")
+     *
+     * Successful Reader:
+     * read sequence (even)
+     * // must see writes from Writer 1 but not Writer 2
+     * r1 = x; r2 = y;
+     * acquireFence();
+     * read sequence (even - validated unchanged)
+     * // use r1 and r2
+     *
+     * Writer 2:
+     * inc sequence (odd - "locked")
+     * storeStoreFence();
+     * x = 3; y = 4;
+     * inc sequence (even - "unlocked")
+     *
+     * Visibility of writer 1's stores is normal - reader's initial
+     * read of state synchronizes with writer 1's final write to state.
+     * Lack of visibility of writer 2's plain writes is less obvious.
+     * If reader's read of x or y saw writer 2's write, then (assuming
+     * semantics of C++ fences) the storeStoreFence would "synchronize"
+     * with reader's acquireFence and reader's validation read must see
+     * writer 2's initial write to state and so validation must fail.
+     * But making this "proof" formal and rigorous is an open problem!
+     * ----------------------------------------------------------------
+     *
      * The memory layout keeps lock state and queue pointers together
      * (normally on the same cache line). This usually works well for
      * read-mostly loads. In most other cases, the natural tendency of
@@ -276,14 +317,14 @@
     /** Number of processors, for spin control */
     private static final int NCPU = Runtime.getRuntime().availableProcessors();
 
-    /** Maximum number of retries before enqueuing on acquisition */
-    private static final int SPINS = (NCPU > 1) ? 1 << 6 : 0;
+    /** Maximum number of retries before enqueuing on acquisition; at least 1 */
+    private static final int SPINS = (NCPU > 1) ? 1 << 6 : 1;
 
-    /** Maximum number of retries before blocking at head on acquisition */
-    private static final int HEAD_SPINS = (NCPU > 1) ? 1 << 10 : 0;
+    /** Maximum number of tries before blocking at head on acquisition */
+    private static final int HEAD_SPINS = (NCPU > 1) ? 1 << 10 : 1;
 
     /** Maximum number of retries before re-blocking */
-    private static final int MAX_HEAD_SPINS = (NCPU > 1) ? 1 << 16 : 0;
+    private static final int MAX_HEAD_SPINS = (NCPU > 1) ? 1 << 16 : 1;
 
     /** The period for yielding when waiting for overflow spinlock */
     private static final int OVERFLOW_YIELD_RATE = 7; // must be power 2 - 1
@@ -1228,6 +1269,11 @@
                         WCOWAIT.compareAndSet(h, c, c.cowait) &&
                         (w = c.thread) != null) // help release
                         LockSupport.unpark(w);
+                    if (Thread.interrupted()) {
+                        if (interruptible)
+                            return cancelWaiter(node, p, true);
+                        wasInterrupted = true;
+                    }
                     if (h == (pp = p.prev) || h == p || pp == null) {
                         long m, s, ns;
                         do {
@@ -1264,11 +1310,6 @@
                                 LockSupport.parkNanos(this, time);
                         }
                         node.thread = null;
-                        if (Thread.interrupted()) {
-                            if (interruptible)
-                                return cancelWaiter(node, p, true);
-                            wasInterrupted = true;
-                        }
                     }
                 }
             }
--- a/jdk/src/java.base/share/classes/jdk/internal/misc/JavaLangInvokeAccess.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/src/java.base/share/classes/jdk/internal/misc/JavaLangInvokeAccess.java	Wed Jul 05 22:05:22 2017 +0200
@@ -25,19 +25,42 @@
 
 package jdk.internal.misc;
 
+import java.lang.invoke.MethodType;
+import java.util.Map;
+
 public interface JavaLangInvokeAccess {
     /**
-     * Create a new MemberName instance
+     * Create a new MemberName instance. Used by {@see StackFrameInfo}.
      */
     Object newMemberName();
 
     /**
-     * Returns the name for the given MemberName
+     * Returns the name for the given MemberName. Used by {@see StackFrameInfo}.
      */
     String getName(Object mname);
 
     /**
-     * Returns {@code true} if the given MemberName is a native method
+     * Returns {@code true} if the given MemberName is a native method. Used by
+     * {@see StackFrameInfo}.
      */
     boolean isNative(Object mname);
+
+    /**
+     * Returns a {@code byte[]} containing the bytecode for a class implementing
+     * DirectMethodHandle of each pairwise combination of {@code MethodType} and
+     * an {@code int} representing method type.  Used by
+     * GenerateJLIClassesPlugin to generate such a class during the jlink phase.
+     */
+    byte[] generateDMHClassBytes(String className, MethodType[] methodTypes,
+            int[] types);
+
+    /**
+     * Returns a {@code byte[]} containing the bytecode for a BoundMethodHandle
+     * species class implementing the signature defined by {@code types}. Used
+     * by GenerateBMHClassesPlugin to enable generation of such classes during
+     * the jlink phase. Should do some added validation since this string may be
+     * user provided.
+     */
+    Map.Entry<String, byte[]> generateConcreteBMHClassBytes(
+            final String types);
 }
--- a/jdk/src/java.base/share/classes/jdk/internal/misc/SharedSecrets.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/src/java.base/share/classes/jdk/internal/misc/SharedSecrets.java	Wed Jul 05 22:05:22 2017 +0200
@@ -95,7 +95,7 @@
     public static JavaLangInvokeAccess getJavaLangInvokeAccess() {
         if (javaLangInvokeAccess == null) {
             try {
-                Class<?> c = Class.forName("java.lang.invoke.MemberName");
+                Class<?> c = Class.forName("java.lang.invoke.MethodHandleImpl");
                 unsafe.ensureClassInitialized(c);
             } catch (ClassNotFoundException e) {};
         }
--- a/jdk/src/java.base/share/classes/jdk/internal/module/ModuleBootstrap.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/src/java.base/share/classes/jdk/internal/module/ModuleBootstrap.java	Wed Jul 05 22:05:22 2017 +0200
@@ -56,8 +56,8 @@
  * The {@link #boot() boot} method is called early in the startup to initialize
  * the module system. In summary, the boot method creates a Configuration by
  * resolving a set of module names specified via the launcher (or equivalent)
- * -m and -addmods options. The modules are located on a module path that is
- * constructed from the upgrade module path, system modules, and application
+ * -m and --add-modules options. The modules are located on a module path that
+ * is constructed from the upgrade module path, system modules, and application
  * module path. The Configuration is instantiated as the boot Layer with each
  * module in the the configuration defined to one of the built-in class loaders.
  */
@@ -127,16 +127,16 @@
 
         long t2 = System.nanoTime();
 
-        // -upgrademodulepath option specified to launcher
+        // --upgrade-module-path option specified to launcher
         ModuleFinder upgradeModulePath
-            = createModulePathFinder("jdk.upgrade.module.path");
+            = createModulePathFinder("jdk.module.upgrade.path");
         if (upgradeModulePath != null)
             systemModules = ModuleFinder.compose(upgradeModulePath, systemModules);
 
-        // -modulepath option specified to the launcher
+        // --module-path option specified to the launcher
         ModuleFinder appModulePath = createModulePathFinder("jdk.module.path");
 
-        // The module finder: [-upgrademodulepath] system [-modulepath]
+        // The module finder: [--upgrade-module-path] system [--module-path]
         ModuleFinder finder = systemModules;
         if (appModulePath != null)
             finder = ModuleFinder.compose(finder, appModulePath);
@@ -149,11 +149,11 @@
         if (mainModule != null)
             roots.add(mainModule);
 
-        // additional module(s) specified by -addmods
+        // additional module(s) specified by --add-modules
         boolean addAllDefaultModules = false;
         boolean addAllSystemModules = false;
         boolean addAllApplicationModules = false;
-        String propValue = System.getProperty("jdk.launcher.addmods");
+        String propValue = getAndRemoveProperty("jdk.module.addmods");
         if (propValue != null) {
             for (String mod: propValue.split(",")) {
                 switch (mod) {
@@ -172,8 +172,8 @@
             }
         }
 
-        // -limitmods
-        propValue = System.getProperty("jdk.launcher.limitmods");
+        // --limit-modules
+        propValue = getAndRemoveProperty("jdk.module.limitmods");
         if (propValue != null) {
             Set<String> mods = new HashSet<>();
             for (String mod: propValue.split(",")) {
@@ -216,7 +216,7 @@
             }
         }
 
-        // If `-addmods ALL-SYSTEM` is specified then all observable system
+        // If `--add-modules ALL-SYSTEM` is specified then all observable system
         // modules will be resolved.
         if (addAllSystemModules) {
             ModuleFinder f = finder;  // observable modules
@@ -228,9 +228,9 @@
                 .forEach(mn -> roots.add(mn));
         }
 
-        // If `-addmods ALL-MODULE-PATH` is specified then all observable
+        // If `--add-modules ALL-MODULE-PATH` is specified then all observable
         // modules on the application module path will be resolved.
-        if  (appModulePath != null && addAllApplicationModules) {
+        if (appModulePath != null && addAllApplicationModules) {
             ModuleFinder f = finder;  // observable modules
             appModulePath.findAll()
                 .stream()
@@ -250,7 +250,7 @@
         if (baseUri.getScheme().equals("jrt")   // toLowerCase not needed here
                 && (upgradeModulePath == null)
                 && (appModulePath == null)
-                && (System.getProperty("jdk.launcher.patch.0") == null)) {
+                && (!ModulePatcher.isBootLayerPatched())) {
             needPostResolutionChecks = false;
         }
 
@@ -317,7 +317,7 @@
         PerfCounters.loadModulesTime.addElapsedTimeFrom(t5);
 
 
-        // -XaddReads and -XaddExports
+        // --add-reads and --add-exports
         addExtraReads(bootLayer);
         addExtraExports(bootLayer);
 
@@ -394,13 +394,13 @@
 
 
     /**
-     * Process the -XaddReads options to add any additional read edges that
+     * Process the --add-reads options to add any additional read edges that
      * are specified on the command-line.
      */
     private static void addExtraReads(Layer bootLayer) {
 
         // decode the command line options
-        Map<String, Set<String>> map = decode("jdk.launcher.addreads.");
+        Map<String, Set<String>> map = decode("jdk.module.addreads.");
 
         for (Map.Entry<String, Set<String>> e : map.entrySet()) {
 
@@ -431,13 +431,13 @@
 
 
     /**
-     * Process the -XaddExports options to add any additional read edges that
+     * Process the --add-exports options to add any additional read edges that
      * are specified on the command-line.
      */
     private static void addExtraExports(Layer bootLayer) {
 
         // decode the command line options
-        Map<String, Set<String>> map = decode("jdk.launcher.addexports.");
+        Map<String, Set<String>> map = decode("jdk.module.addexports.");
 
         for (Map.Entry<String, Set<String>> e : map.entrySet()) {
 
@@ -483,13 +483,14 @@
 
 
     /**
-     * Decodes the values of -XaddReads or -XaddExports options
+     * Decodes the values of --add-reads or --add-exports options
      *
      * The format of the options is: $KEY=$MODULE(,$MODULE)*
      */
     private static Map<String, Set<String>> decode(String prefix) {
         int index = 0;
-        String value = System.getProperty(prefix + index);
+        // the system property is removed after decoding
+        String value = getAndRemoveProperty(prefix + index);
         if (value == null)
             return Collections.emptyMap();
 
@@ -522,12 +523,18 @@
             }
 
             index++;
-            value = System.getProperty(prefix + index);
+            value = getAndRemoveProperty(prefix + index);
         }
 
         return map;
     }
 
+    /**
+     * Gets and remove the named system property
+     */
+    private static String getAndRemoveProperty(String key) {
+        return (String)System.getProperties().remove(key);
+    }
 
     /**
      * Throws a RuntimeException with the given message
--- a/jdk/src/java.base/share/classes/jdk/internal/module/ModulePatcher.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/src/java.base/share/classes/jdk/internal/module/ModulePatcher.java	Wed Jul 05 22:05:22 2017 +0200
@@ -58,7 +58,7 @@
 
 
 /**
- * Provides support for patching modules in the boot layer with -Xpatch.
+ * Provides support for patching modules in the boot layer with --patch-module.
  */
 
 public final class ModulePatcher {
@@ -66,28 +66,27 @@
     private static final JavaLangModuleAccess JLMA
         = SharedSecrets.getJavaLangModuleAccess();
 
-    // the prefix of the system properties that encode the value of -Xpatch
-    private static final String PATCH_PROPERTY_PREFIX = "jdk.launcher.patch.";
+    // the prefix of the system properties that encode the value of --patch-module
+    private static final String PATCH_PROPERTY_PREFIX = "jdk.module.patch.";
 
     // module name -> sequence of patches (directories or JAR files)
     private static final Map<String, List<Path>> PATCH_MAP = decodeProperties();
 
     private ModulePatcher() { }
 
-
     /**
-     * Decodes the values of -Xpatch options, returning a Map of module name to
-     * list of file paths.
+     * Decodes the values of --patch-module options, returning a Map of module
+     * name to list of file paths.
      *
      * @throws IllegalArgumentException if the the module name is missing or
-     *         -Xpatch is used more than once to patch the same module
+     *         --patch-module is used more than once to patch the same module
      */
     private static Map<String, List<Path>> decodeProperties() {
 
         int index = 0;
-        String value = System.getProperty(PATCH_PROPERTY_PREFIX + index);
+        String value = getAndRemoveProperty(PATCH_PROPERTY_PREFIX + index);
         if (value == null)
-            return Collections.emptyMap();  // -Xpatch not specified
+            return Collections.emptyMap();  // --patch-module not specified
 
         Map<String, List<Path>> map = new HashMap<>();
         while (value != null) {
@@ -115,7 +114,7 @@
             }
 
             index++;
-            value = System.getProperty(PATCH_PROPERTY_PREFIX + index);
+            value = getAndRemoveProperty(PATCH_PROPERTY_PREFIX + index);
         }
 
         return map;
@@ -123,6 +122,14 @@
 
 
     /**
+     * Returns {@code true} is --patch-module is specified to patch modules
+     * in the boot layer.
+     */
+    static boolean isBootLayerPatched() {
+        return !PATCH_MAP.isEmpty();
+    }
+
+    /**
      * Returns a module reference that interposes on the given module if
      * needed. If there are no patches for the given module then the module
      * reference is simply returned. Otherwise the patches for the module
@@ -537,6 +544,13 @@
     }
 
     /**
+     * Gets and remove the named system property
+     */
+    private static String getAndRemoveProperty(String key) {
+        return (String)System.getProperties().remove(key);
+    }
+
+    /**
      * Derives a package name from the name of an entry in a JAR file.
      */
     private static String toPackageName(Path file, JarEntry entry) {
--- a/jdk/src/java.base/share/classes/module-info.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/src/java.base/share/classes/module-info.java	Wed Jul 05 22:05:22 2017 +0200
@@ -128,6 +128,7 @@
     exports jdk.internal.logger to
         java.logging;
     exports jdk.internal.org.objectweb.asm to
+        jdk.jartool,
         jdk.jlink,
         jdk.scripting.nashorn,
         jdk.vm.ci;
--- a/jdk/src/java.base/share/classes/sun/invoke/util/ValueConversions.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/src/java.base/share/classes/sun/invoke/util/ValueConversions.java	Wed Jul 05 22:05:22 2017 +0200
@@ -29,27 +29,32 @@
 import java.lang.invoke.MethodHandles;
 import java.lang.invoke.MethodHandles.Lookup;
 import java.lang.invoke.MethodType;
-import java.util.EnumMap;
+import jdk.internal.vm.annotation.Stable;
 
 public class ValueConversions {
     private static final Class<?> THIS_CLASS = ValueConversions.class;
     private static final Lookup IMPL_LOOKUP = MethodHandles.lookup();
 
-    /** Thread-safe canonicalized mapping from Wrapper to MethodHandle
+    /**
+     * Thread-safe canonicalized mapping from Wrapper to MethodHandle
      * with unsynchronized reads and synchronized writes.
-     * It's safe to publish MethodHandles by data race because they are immutable. */
+     * It's safe to publish MethodHandles by data race because they are immutable.
+     */
     private static class WrapperCache {
-        /** EnumMap uses preconstructed array internally, which is constant during it's lifetime. */
-        private final EnumMap<Wrapper, MethodHandle> map = new EnumMap<>(Wrapper.class);
+        @Stable
+        private final MethodHandle[] map = new MethodHandle[Wrapper.COUNT];
 
         public MethodHandle get(Wrapper w) {
-            return map.get(w);
+            return map[w.ordinal()];
         }
         public synchronized MethodHandle put(final Wrapper w, final MethodHandle mh) {
-            // Simulate CAS to avoid racy duplication
-            MethodHandle prev = map.putIfAbsent(w, mh);
-            if (prev != null)  return prev;
-            return mh;
+            MethodHandle prev = map[w.ordinal()];
+            if (prev != null) {
+                return prev;
+            } else {
+                map[w.ordinal()] = mh;
+                return mh;
+            }
         }
     }
 
@@ -623,7 +628,7 @@
         return (x ? (byte)1 : (byte)0);
     }
 
-    private static final WrapperCache[] CONVERT_PRIMITIVE_FUNCTIONS = newWrapperCaches(Wrapper.values().length);
+    private static final WrapperCache[] CONVERT_PRIMITIVE_FUNCTIONS = newWrapperCaches(Wrapper.COUNT);
 
     public static MethodHandle convertPrimitive(Wrapper wsrc, Wrapper wdst) {
         WrapperCache cache = CONVERT_PRIMITIVE_FUNCTIONS[wsrc.ordinal()];
--- a/jdk/src/java.base/share/classes/sun/invoke/util/VerifyAccess.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/src/java.base/share/classes/sun/invoke/util/VerifyAccess.java	Wed Jul 05 22:05:22 2017 +0200
@@ -28,6 +28,7 @@
 import java.lang.reflect.Modifier;
 import static java.lang.reflect.Modifier.*;
 import java.lang.reflect.Module;
+import java.util.Objects;
 import jdk.internal.reflect.Reflection;
 
 /**
@@ -330,15 +331,7 @@
             return true;
         if (class1.getClassLoader() != class2.getClassLoader())
             return false;
-        String name1 = class1.getName(), name2 = class2.getName();
-        int dot = name1.lastIndexOf('.');
-        if (dot != name2.lastIndexOf('.'))
-            return false;
-        for (int i = 0; i < dot; i++) {
-            if (name1.charAt(i) != name2.charAt(i))
-                return false;
-        }
-        return true;
+        return Objects.equals(class1.getPackageName(), class2.getPackageName());
     }
 
     /** Return the package name for this class.
--- a/jdk/src/java.base/share/classes/sun/invoke/util/Wrapper.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/src/java.base/share/classes/sun/invoke/util/Wrapper.java	Wed Jul 05 22:05:22 2017 +0200
@@ -42,6 +42,8 @@
     VOID   (     Void.class,    void.class, 'V',           null, Format.other(    0)),
     ;
 
+    public static final int COUNT = 10;
+
     private final Class<?> wrapperType;
     private final Class<?> primitiveType;
     private final char     basicTypeChar;
@@ -160,7 +162,10 @@
         return true;
     }
 
-    static { assert(checkConvertibleFrom()); }
+    static {
+        assert(checkConvertibleFrom());
+        assert(COUNT == Wrapper.values().length);
+    }
     private static boolean checkConvertibleFrom() {
         // Check the matrix for correct classification of widening conversions.
         for (Wrapper w : values()) {
--- a/jdk/src/java.base/share/classes/sun/launcher/LauncherHelper.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/src/java.base/share/classes/sun/launcher/LauncherHelper.java	Wed Jul 05 22:05:22 2017 +0200
@@ -60,8 +60,6 @@
 import java.nio.file.DirectoryStream;
 import java.nio.file.Files;
 import java.nio.file.Path;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
 import java.text.Normalizer;
 import java.text.MessageFormat;
 import java.util.ResourceBundle;
@@ -905,7 +903,7 @@
 
         ModuleFinder finder = jdk.internal.module.ModuleBootstrap.finder();
 
-        int colon = optionFlag.indexOf(':');
+        int colon = optionFlag.indexOf('=');
         if (colon == -1) {
             finder.findAll().stream()
                 .sorted(Comparator.comparing(ModuleReference::descriptor))
--- a/jdk/src/java.base/share/classes/sun/launcher/resources/launcher.properties	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/src/java.base/share/classes/sun/launcher/resources/launcher.properties	Wed Jul 05 22:05:22 2017 +0200
@@ -27,7 +27,7 @@
 java.launcher.opt.header  =   Usage: {0} [options] class [args...]\n\
 \           (to execute a class)\n   or  {0} [options] -jar jarfile [args...]\n\
 \           (to execute a jar file)\n\
-\   or  {0} [options] -mp <modulepath> -m <modulename>[/<mainclass>] [args...]\n\
+\   or  {0} [options] -p <modulepath> -m <modulename>[/<mainclass>] [args...]\n\
 \           (to execute the main class in a module)\n\
 where options include:\n
 
@@ -41,24 +41,28 @@
 # Translators please note do not translate the options themselves
 java.launcher.opt.footer     =\    -cp <class search path of directories and zip/jar files>\n\
 \    -classpath <class search path of directories and zip/jar files>\n\
+\    --class-path <class search path of directories and zip/jar files>\n\
 \                  A {0} separated list of directories, JAR archives,\n\
 \                  and ZIP archives to search for class files.\n\
-\    -mp <module path>\n\
-\    -modulepath <module path>...\n\
+\    -p <module path>\n\
+\    --module-path <module path>...\n\
 \                  A {0} separated list of directories, each directory\n\
 \                  is a directory of modules.\n\
-\    -upgrademodulepath <module path>...\n\
+\    --upgrade-module-path <module path>...\n\
 \                  A {0} separated list of directories, each directory\n\
 \                  is a directory of modules that replace upgradeable\n\
 \                  modules in the runtime image\n\
-\    -m <modulename>[/<mainclass>]\n\
+\    -m <module>[/<mainclass>]\n\
+\    --module <modulename>[/<mainclass>]\n\
 \                  the initial module to resolve, and the name of the main class\n\
 \                  to execute if not specified by the module\n\
-\    -addmods <modulename>[,<modulename>...]\n\
-\                  root modules to resolve in addition to the initial module\n\
-\    -limitmods <modulename>[,<modulename>...]\n\
+\    --add-modules <modulename>[,<modulename>...]\n\
+\                  root modules to resolve in addition to the initial module.\n\
+\                  <modulename> can also be ALL-DEFAULT, ALL-SYSTEM,\n\
+\                  ALL-MODULE-PATH.\n\
+\    --limit-modules <modulename>[,<modulename>...]\n\
 \                  limit the universe of observable modules\n\
-\    -listmods[:<modulename>[,<modulename>...]]\n\
+\    --list-modules [<modulename>[,<modulename>...]]\n\
 \                  list the observable modules and exit\n\
 \    --dry-run     create VM but do not execute main method.\n\
 \                  This --dry-run option may be useful for validating the\n\
@@ -69,7 +73,8 @@
 \                  enable verbose output\n\
 \    -version      print product version and exit\n\
 \    -showversion  print product version and continue\n\
-\    -? -help      print this help message\n\
+\    -? -help --help\n\
+\                  print this help message\n\
 \    -X            print help on non-standard options\n\
 \    -ea[:<packagename>...|:<classname>]\n\
 \    -enableassertions[:<packagename>...|:<classname>]\n\
@@ -91,6 +96,8 @@
 \    -splash:<imagepath>\n\
 \                  show splash screen with specified image\n\
 \    @<filepath>   read options from the specified file\n\
+\To specify an argument for a long option, you can use --<name>=<value> or\n\
+\--<name> <value>.\n\
 
 See http://www.oracle.com/technetwork/java/javase/documentation/index.html for more details.
 
@@ -123,17 +130,21 @@
 \                      show all property settings and continue\n\
 \    -XshowSettings:locale\n\
 \                      show all locale related settings and continue\n\
-\    -XaddReads:<module>=<other-module>(,<other-module>)*\n\
-\                      <module> reads other modules,\n\
-\                      regardless of module declaration\n\
-\    -XaddExports:<module>/<package>=<other-module>(,<other-module>)*\n\
-\                      <module> exports <package> to other modules,\n\
-\                      regardless of module declaration\n\
-\    -Xpatch:<module>=<file>({0}<file>)*\n\
+\    -Xdisable-@files  disable further argument file expansion\n\
+\    --add-reads <module>=<target-module>(,<target-module>)*\n\
+\                      updates <module> to read <target-module>, regardless\n\
+\                      of module declaration. \n\
+\                      <target-module> can be ALL-UNNAMED to read all unnamed\n\
+\                      modules.\n\
+\    --add-exports <module>/<package>=<target-module>(,<target-module>)*\n\
+\                      updates <module> to export <package> to <target-module>,\n\
+\                      regardless of module declaration.\n\
+\                      <target-module> can be ALL-UNNAMED to export to all\n\
+\                      unnamed modules.\n\
+\    --patch-module <module>=<file>({0}<file>)*\n\
 \                      Override or augment a module with classes and resources\n\
-\                      in JAR files or directories\n\
-\    -Xdisable-@files  disable further argument file expansion\n\n\
-The -X options are non-standard and subject to change without notice.\n
+\                      in JAR files or directories.\n\n\
+These options are non-standard and subject to change without notice.\n
 
 # Translators please note do not translate the options themselves
 java.launcher.X.macosx.usage=\
--- a/jdk/src/java.base/share/classes/sun/security/pkcs12/PKCS12KeyStore.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/src/java.base/share/classes/sun/security/pkcs12/PKCS12KeyStore.java	Wed Jul 05 22:05:22 2017 +0200
@@ -580,6 +580,9 @@
             Entry entry;
 
             if (key instanceof PrivateKey) {
+                // Check that all the certs are X.509 certs
+                checkX509Certs(chain);
+
                 PrivateKeyEntry keyEntry = new PrivateKeyEntry();
                 keyEntry.date = new Date();
 
@@ -690,6 +693,9 @@
                                   Certificate[] chain)
         throws KeyStoreException
     {
+        // Check that all the certs are X.509 certs
+        checkX509Certs(chain);
+
         // Private key must be encoded as EncryptedPrivateKeyInfo
         // as defined in PKCS#8
         try {
@@ -960,6 +966,13 @@
     private void setCertEntry(String alias, Certificate cert,
         Set<KeyStore.Entry.Attribute> attributes) throws KeyStoreException {
 
+        // Check that the cert is an X.509 cert
+        if (cert != null && (!(cert instanceof X509Certificate))) {
+            throw new KeyStoreException(
+                "Only X.509 certificates are supported - rejecting class: " +
+                cert.getClass().getName());
+        }
+
         Entry entry = entries.get(alias.toLowerCase(Locale.ENGLISH));
         if (entry != null && entry instanceof KeyEntry) {
             throw new KeyStoreException("Cannot overwrite own certificate");
@@ -1505,6 +1518,21 @@
         return set.size() == certChain.length;
     }
 
+    /*
+     * Check that all the certificates are X.509 certificates
+     */
+    private static void checkX509Certs(Certificate[] certs)
+            throws KeyStoreException {
+        if (certs != null) {
+            for (Certificate cert : certs) {
+                if (!(cert instanceof X509Certificate)) {
+                    throw new KeyStoreException(
+                        "Only X.509 certificates are supported - " +
+                        "rejecting class: " + cert.getClass().getName());
+                }
+            }
+        }
+    }
 
     /*
      * Create PKCS#12 Attributes, friendlyName, localKeyId and trustedKeyUsage.
--- a/jdk/src/java.base/share/classes/sun/security/ssl/SSLContextImpl.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/src/java.base/share/classes/sun/security/ssl/SSLContextImpl.java	Wed Jul 05 22:05:22 2017 +0200
@@ -59,6 +59,11 @@
             "jdk.tls.client.enableStatusRequestExtension", true);
     private final boolean serverEnableStapling = Debug.getBooleanProperty(
             "jdk.tls.server.enableStatusRequestExtension", false);
+    private final static Collection<CipherSuite> clientCustomizedCipherSuites =
+            getCustomizedCipherSuites("jdk.tls.client.cipherSuites");
+    private final static Collection<CipherSuite> serverCustomizedCipherSuites =
+            getCustomizedCipherSuites("jdk.tls.server.cipherSuites");
+
     private volatile StatusResponseManager statusResponseManager;
 
     SSLContextImpl() {
@@ -336,20 +341,52 @@
         return isClient ? clientEnableStapling : serverEnableStapling;
     }
 
+
     /*
-     * Return the list of all available CipherSuites with a priority of
-     * minPriority or above.
+     * Return the list of all available CipherSuites that are supported
+     * using currently installed providers.
+     */
+    private static CipherSuiteList getApplicableSupportedCipherSuiteList(
+            ProtocolList protocols) {
+
+        return getApplicableCipherSuiteList(
+                CipherSuite.allowedCipherSuites(),
+                protocols, CipherSuite.SUPPORTED_SUITES_PRIORITY);
+    }
+
+    /*
+     * Return the list of all available CipherSuites that are default enabled
+     * in client or server side.
+     */
+    private static CipherSuiteList getApplicableEnabledCipherSuiteList(
+            ProtocolList protocols, boolean isClient) {
+
+        if (isClient) {
+            if (!clientCustomizedCipherSuites.isEmpty()) {
+                return getApplicableCipherSuiteList(
+                        clientCustomizedCipherSuites,
+                        protocols, CipherSuite.SUPPORTED_SUITES_PRIORITY);
+            }
+        } else {
+            if (!serverCustomizedCipherSuites.isEmpty()) {
+                return getApplicableCipherSuiteList(
+                        serverCustomizedCipherSuites,
+                        protocols, CipherSuite.SUPPORTED_SUITES_PRIORITY);
+            }
+        }
+
+        return getApplicableCipherSuiteList(
+                CipherSuite.allowedCipherSuites(),
+                protocols, CipherSuite.DEFAULT_SUITES_PRIORITY);
+    }
+
+    /*
+     * Return the list of available CipherSuites which are applicable to
+     * the specified protocols.
      */
     private static CipherSuiteList getApplicableCipherSuiteList(
-            ProtocolList protocols, boolean onlyEnabled) {
-
-        int minPriority = CipherSuite.SUPPORTED_SUITES_PRIORITY;
-        if (onlyEnabled) {
-            minPriority = CipherSuite.DEFAULT_SUITES_PRIORITY;
-        }
-
-        Collection<CipherSuite> allowedCipherSuites =
-                                    CipherSuite.allowedCipherSuites();
+            Collection<CipherSuite> allowedCipherSuites,
+            ProtocolList protocols, int minPriority) {
 
         TreeSet<CipherSuite> suites = new TreeSet<>();
         if (!(protocols.collection().isEmpty()) &&
@@ -386,6 +423,67 @@
         return new CipherSuiteList(suites);
     }
 
+    /*
+     * Get the customized cipher suites specified by the given system property.
+     */
+    private static Collection<CipherSuite> getCustomizedCipherSuites(
+            String propertyName) {
+
+        String property = GetPropertyAction.privilegedGetProperty(propertyName);
+        if (debug != null && Debug.isOn("sslctx")) {
+            System.out.println(
+                    "System property " + propertyName + " is set to '" +
+                    property + "'");
+        }
+        if (property != null && property.length() != 0) {
+            // remove double quote marks from beginning/end of the property
+            if (property.length() > 1 && property.charAt(0) == '"' &&
+                    property.charAt(property.length() - 1) == '"') {
+                property = property.substring(1, property.length() - 1);
+            }
+        }
+
+        if (property != null && property.length() != 0) {
+            String[] cipherSuiteNames = property.split(",");
+            Collection<CipherSuite> cipherSuites =
+                        new ArrayList<>(cipherSuiteNames.length);
+            for (int i = 0; i < cipherSuiteNames.length; i++) {
+                cipherSuiteNames[i] = cipherSuiteNames[i].trim();
+                if (cipherSuiteNames[i].isEmpty()) {
+                    continue;
+                }
+
+                CipherSuite suite;
+                try {
+                    suite = CipherSuite.valueOf(cipherSuiteNames[i]);
+                } catch (IllegalArgumentException iae) {
+                    if (debug != null && Debug.isOn("sslctx")) {
+                        System.out.println(
+                                "Unknown or unsupported cipher suite name: " +
+                                cipherSuiteNames[i]);
+                    }
+
+                    continue;
+                }
+
+                if (suite.isAvailable()) {
+                    cipherSuites.add(suite);
+                } else {
+                    if (debug != null && Debug.isOn("sslctx")) {
+                        System.out.println(
+                                "The current installed providers do not " +
+                                "support cipher suite: " + cipherSuiteNames[i]);
+                    }
+                }
+            }
+
+            return cipherSuites;
+        }
+
+        return Collections.emptyList();
+    }
+
+
     private static String[] getAvailableProtocols(
             ProtocolVersion[] protocolCandidates) {
 
@@ -481,10 +579,10 @@
                 }));
             }
 
-            supportedCipherSuiteList = getApplicableCipherSuiteList(
-                    supportedProtocolList, false);          // all supported
-            serverDefaultCipherSuiteList = getApplicableCipherSuiteList(
-                    serverDefaultProtocolList, true);       // enabled only
+            supportedCipherSuiteList = getApplicableSupportedCipherSuiteList(
+                    supportedProtocolList);
+            serverDefaultCipherSuiteList = getApplicableEnabledCipherSuiteList(
+                    serverDefaultProtocolList, false);
         }
 
         @Override
@@ -541,8 +639,8 @@
                 }));
             }
 
-            clientDefaultCipherSuiteList = getApplicableCipherSuiteList(
-                    clientDefaultProtocolList, true);       // enabled only
+            clientDefaultCipherSuiteList = getApplicableEnabledCipherSuiteList(
+                    clientDefaultProtocolList, true);
         }
 
         @Override
@@ -581,8 +679,9 @@
                 }));
             }
 
-            clientDefaultCipherSuiteList = getApplicableCipherSuiteList(
-                    clientDefaultProtocolList, true);       // enabled only
+            clientDefaultCipherSuiteList = getApplicableEnabledCipherSuiteList(
+                    clientDefaultProtocolList, true);
+
         }
 
         @Override
@@ -623,8 +722,8 @@
                 }));
             }
 
-            clientDefaultCipherSuiteList = getApplicableCipherSuiteList(
-                    clientDefaultProtocolList, true);       // enabled only
+            clientDefaultCipherSuiteList = getApplicableEnabledCipherSuiteList(
+                    clientDefaultProtocolList, true);
         }
 
         @Override
@@ -757,8 +856,9 @@
 
                 clientDefaultProtocolList = new ProtocolList(
                         getAvailableProtocols(candidates));
-                clientDefaultCipherSuiteList = getApplicableCipherSuiteList(
-                    clientDefaultProtocolList, true);   // enabled only
+                clientDefaultCipherSuiteList =
+                        getApplicableEnabledCipherSuiteList(
+                                clientDefaultProtocolList, true);
             } else {
                 clientDefaultProtocolList = null;       // unlikely to be used
                 clientDefaultCipherSuiteList = null;    // unlikely to be used
@@ -1032,10 +1132,10 @@
                 ProtocolVersion.DTLS12
             }));
 
-            supportedCipherSuiteList = getApplicableCipherSuiteList(
-                    supportedProtocolList, false);          // all supported
-            serverDefaultCipherSuiteList = getApplicableCipherSuiteList(
-                    serverDefaultProtocolList, true);       // enabled only
+            supportedCipherSuiteList = getApplicableSupportedCipherSuiteList(
+                    supportedProtocolList);
+            serverDefaultCipherSuiteList = getApplicableEnabledCipherSuiteList(
+                    serverDefaultProtocolList, false);
         }
 
         @Override
@@ -1090,8 +1190,8 @@
                 ProtocolVersion.DTLS10
             }));
 
-            clientDefaultCipherSuiteList = getApplicableCipherSuiteList(
-                    clientDefaultProtocolList, true);       // enabled only
+            clientDefaultCipherSuiteList = getApplicableEnabledCipherSuiteList(
+                    clientDefaultProtocolList, true);
         }
 
         @Override
@@ -1122,8 +1222,8 @@
                 ProtocolVersion.DTLS12
             }));
 
-            clientDefaultCipherSuiteList = getApplicableCipherSuiteList(
-                    clientDefaultProtocolList, true);       // enabled only
+            clientDefaultCipherSuiteList = getApplicableEnabledCipherSuiteList(
+                    clientDefaultProtocolList, true);
         }
 
         @Override
@@ -1187,8 +1287,9 @@
 
                 clientDefaultProtocolList = new ProtocolList(
                         getAvailableProtocols(candidates));
-                clientDefaultCipherSuiteList = getApplicableCipherSuiteList(
-                    clientDefaultProtocolList, true);   // enabled only
+                clientDefaultCipherSuiteList =
+                        getApplicableEnabledCipherSuiteList(
+                                clientDefaultProtocolList, true);
             } else {
                 clientDefaultProtocolList = null;       // unlikely to be used
                 clientDefaultCipherSuiteList = null;    // unlikely to be used
--- a/jdk/src/java.base/share/classes/sun/security/ssl/ServerHandshaker.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/src/java.base/share/classes/sun/security/ssl/ServerHandshaker.java	Wed Jul 05 22:05:22 2017 +0200
@@ -1994,7 +1994,7 @@
 
     private StaplingParameters processStapling(ClientHello mesg) {
         StaplingParameters params = null;
-        ExtensionType ext;
+        ExtensionType ext = null;
         StatusRequestType type = null;
         StatusRequest req = null;
         Map<X509Certificate, byte[]> responses;
@@ -2012,33 +2012,40 @@
         CertStatusReqListV2Extension statReqExtV2 =
                 (CertStatusReqListV2Extension)mesg.extensions.get(
                         ExtensionType.EXT_STATUS_REQUEST_V2);
-        // Keep processing only if either status_request or status_request_v2
-        // has been sent in the ClientHello.
-        if (statReqExt == null && statReqExtV2 == null) {
-            return null;
-        }
 
         // Determine which type of stapling we are doing and assert the
         // proper extension in the server hello.
         // Favor status_request_v2 over status_request and ocsp_multi
         // over ocsp.
         // If multiple ocsp or ocsp_multi types exist, select the first
-        // instance of a given type
-        ext = ExtensionType.EXT_STATUS_REQUEST;
+        // instance of a given type.  Also since we don't support ResponderId
+        // selection yet, only accept a request if the ResponderId field
+        // is empty.
         if (statReqExtV2 != null) {             // RFC 6961 stapling
             ext = ExtensionType.EXT_STATUS_REQUEST_V2;
             List<CertStatusReqItemV2> reqItems =
                     statReqExtV2.getRequestItems();
             int ocspIdx = -1;
             int ocspMultiIdx = -1;
-            for (int pos = 0; pos < reqItems.size(); pos++) {
+            for (int pos = 0; (pos < reqItems.size() &&
+                    (ocspIdx == -1 || ocspMultiIdx == -1)); pos++) {
                 CertStatusReqItemV2 item = reqItems.get(pos);
-                if (ocspIdx < 0 && item.getType() ==
-                        StatusRequestType.OCSP) {
-                    ocspIdx = pos;
-                } else if (ocspMultiIdx < 0 && item.getType() ==
-                        StatusRequestType.OCSP_MULTI) {
-                    ocspMultiIdx = pos;
+                StatusRequestType curType = item.getType();
+                if (ocspIdx < 0 && curType == StatusRequestType.OCSP) {
+                    OCSPStatusRequest ocspReq =
+                            (OCSPStatusRequest)item.getRequest();
+                    if (ocspReq.getResponderIds().isEmpty()) {
+                        ocspIdx = pos;
+                    }
+                } else if (ocspMultiIdx < 0 &&
+                        curType == StatusRequestType.OCSP_MULTI) {
+                    // If the type is OCSP, then the request
+                    // is guaranteed to be OCSPStatusRequest
+                    OCSPStatusRequest ocspReq =
+                            (OCSPStatusRequest)item.getRequest();
+                    if (ocspReq.getResponderIds().isEmpty()) {
+                        ocspMultiIdx = pos;
+                    }
                 }
             }
             if (ocspMultiIdx >= 0) {
@@ -2047,16 +2054,47 @@
             } else if (ocspIdx >= 0) {
                 type = reqItems.get(ocspIdx).getType();
                 req = reqItems.get(ocspIdx).getRequest();
+            } else {
+                if (debug != null && Debug.isOn("handshake")) {
+                    System.out.println("Warning: No suitable request " +
+                            "found in the status_request_v2 extension.");
+                }
             }
-        } else {                                // RFC 6066 stapling
-            type = StatusRequestType.OCSP;
-            req = statReqExt.getRequest();
+        }
+
+        // Only attempt to process a status_request extension if:
+        // * The status_request extension is set AND
+        // * either the status_request_v2 extension is not present OR
+        // * none of the underlying OCSPStatusRequest structures is suitable
+        // for stapling.
+        // If either of the latter two bullet items is true the ext, type and
+        // req variables should all be null.  If any are null we will try
+        // processing an asserted status_request.
+        if ((statReqExt != null) &&
+               (ext == null || type == null || req == null)) {
+            ext = ExtensionType.EXT_STATUS_REQUEST;
+            type = statReqExt.getType();
+            if (type == StatusRequestType.OCSP) {
+                // If the type is OCSP, then the request is guaranteed
+                // to be OCSPStatusRequest
+                OCSPStatusRequest ocspReq =
+                        (OCSPStatusRequest)statReqExt.getRequest();
+                if (ocspReq.getResponderIds().isEmpty()) {
+                    req = ocspReq;
+                } else {
+                    if (debug != null && Debug.isOn("handshake")) {
+                        req = null;
+                        System.out.println("Warning: No suitable request " +
+                                "found in the status_request extension.");
+                    }
+                }
+            }
         }
 
         // If, after walking through the extensions we were unable to
         // find a suitable StatusRequest, then stapling is disabled.
-        // Both statReqType and statReqData must have been set to continue.
-        if (type == null || req == null) {
+        // The ext, type and req variables must have been set to continue.
+        if (type == null || req == null || ext == null) {
             return null;
         }
 
--- a/jdk/src/java.base/share/classes/sun/security/tools/KeyStoreUtil.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/src/java.base/share/classes/sun/security/tools/KeyStoreUtil.java	Wed Jul 05 22:05:22 2017 +0200
@@ -63,8 +63,6 @@
         // this class is not meant to be instantiated
     }
 
-    private static final String JKS = "jks";
-
     private static final Collator collator = Collator.getInstance();
     static {
         // this is for case insensitive string comparisons
@@ -113,24 +111,24 @@
     }
 
     /**
+     * Returns the file name of the keystore with the configured CA certificates.
+     */
+    public static String getCacerts() {
+        String sep = File.separator;
+        return System.getProperty("java.home") + sep
+                + "lib" + sep + "security" + sep
+                + "cacerts";
+    }
+
+    /**
      * Returns the keystore with the configured CA certificates.
      */
-    public static KeyStore getCacertsKeyStore()
-        throws Exception
-    {
-        String sep = File.separator;
-        File file = new File(System.getProperty("java.home") + sep
-                             + "lib" + sep + "security" + sep
-                             + "cacerts");
+    public static KeyStore getCacertsKeyStore() throws Exception {
+        File file = new File(getCacerts());
         if (!file.exists()) {
             return null;
         }
-        KeyStore caks = null;
-        try (FileInputStream fis = new FileInputStream(file)) {
-            caks = KeyStore.getInstance(JKS);
-            caks.load(fis, null);
-        }
-        return caks;
+        return KeyStore.getInstance(file, (char[])null);
     }
 
     public static char[] getPassWithModifier(String modifier, String arg,
--- a/jdk/src/java.base/share/classes/sun/security/tools/keytool/Main.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/src/java.base/share/classes/sun/security/tools/keytool/Main.java	Wed Jul 05 22:05:22 2017 +0200
@@ -153,6 +153,7 @@
     private boolean trustcacerts = false;
     private boolean protectedPath = false;
     private boolean srcprotectedPath = false;
+    private boolean cacerts = false;
     private CertificateFactory cf = null;
     private KeyStore caks = null; // "cacerts" keystore
     private char[] srcstorePass = null;
@@ -169,15 +170,15 @@
             STOREPASS, STORETYPE, PROVIDERNAME, ADDPROVIDER,
             PROVIDERCLASS, PROVIDERPATH, V, PROTECTED),
         CHANGEALIAS("Changes.an.entry.s.alias",
-            ALIAS, DESTALIAS, KEYPASS, KEYSTORE, STOREPASS,
+            ALIAS, DESTALIAS, KEYPASS, KEYSTORE, CACERTS, STOREPASS,
             STORETYPE, PROVIDERNAME, ADDPROVIDER, PROVIDERCLASS,
             PROVIDERPATH, V, PROTECTED),
         DELETE("Deletes.an.entry",
-            ALIAS, KEYSTORE, STOREPASS, STORETYPE,
+            ALIAS, KEYSTORE, CACERTS, STOREPASS, STORETYPE,
             PROVIDERNAME, ADDPROVIDER, PROVIDERCLASS,
             PROVIDERPATH, V, PROTECTED),
         EXPORTCERT("Exports.certificate",
-            RFC, ALIAS, FILEOUT, KEYSTORE, STOREPASS,
+            RFC, ALIAS, FILEOUT, KEYSTORE, CACERTS, STOREPASS,
             STORETYPE, PROVIDERNAME, ADDPROVIDER, PROVIDERCLASS,
             PROVIDERPATH, V, PROTECTED),
         GENKEYPAIR("Generates.a.key.pair",
@@ -196,7 +197,7 @@
             PROVIDERCLASS, PROVIDERPATH, V, PROTECTED),
         IMPORTCERT("Imports.a.certificate.or.a.certificate.chain",
             NOPROMPT, TRUSTCACERTS, PROTECTED, ALIAS, FILEIN,
-            KEYPASS, KEYSTORE, STOREPASS, STORETYPE,
+            KEYPASS, KEYSTORE, CACERTS, STOREPASS, STORETYPE,
             PROVIDERNAME, ADDPROVIDER, PROVIDERCLASS,
             PROVIDERPATH, V),
         IMPORTPASS("Imports.a.password",
@@ -215,7 +216,7 @@
             STORETYPE, PROVIDERNAME, ADDPROVIDER, PROVIDERCLASS,
             PROVIDERPATH, V),
         LIST("Lists.entries.in.a.keystore",
-            RFC, ALIAS, KEYSTORE, STOREPASS, STORETYPE,
+            RFC, ALIAS, KEYSTORE, CACERTS, STOREPASS, STORETYPE,
             PROVIDERNAME, ADDPROVIDER, PROVIDERCLASS,
             PROVIDERPATH, V, PROTECTED),
         PRINTCERT("Prints.the.content.of.a.certificate",
@@ -225,7 +226,7 @@
         PRINTCRL("Prints.the.content.of.a.CRL.file",
             FILEIN, V),
         STOREPASSWD("Changes.the.store.password.of.a.keystore",
-            NEW, KEYSTORE, STOREPASS, STORETYPE, PROVIDERNAME,
+            NEW, KEYSTORE, CACERTS, STOREPASS, STORETYPE, PROVIDERNAME,
             ADDPROVIDER, PROVIDERCLASS, PROVIDERPATH, V),
 
         // Undocumented start here, KEYCLONE is used a marker in -help;
@@ -306,6 +307,7 @@
         KEYPASS("keypass", "<arg>", "key.password"),
         KEYSIZE("keysize", "<size>", "key.bit.size"),
         KEYSTORE("keystore", "<keystore>", "keystore.name"),
+        CACERTS("cacerts", null, "access.the.cacerts.keystore"),
         NEW("new", "<arg>", "new.password"),
         NOPROMPT("noprompt", null, "do.not.prompt"),
         OUTFILE("outfile", "<file>", "output.file.name"),
@@ -472,14 +474,16 @@
                 help = true;
             } else if (collator.compare(flags, "-conf") == 0) {
                 i++;
-            }
-
-            /*
-             * specifiers
-             */
-            else if (collator.compare(flags, "-keystore") == 0 ||
-                    collator.compare(flags, "-destkeystore") == 0) {
+            } else if (collator.compare(flags, "-keystore") == 0) {
                 ksfname = args[++i];
+                if (new File(ksfname).getCanonicalPath().equals(
+                        new File(KeyStoreUtil.getCacerts()).getCanonicalPath())) {
+                    System.err.println(rb.getString("warning.cacerts.option"));
+                }
+            } else if (collator.compare(flags, "-destkeystore") == 0) {
+                ksfname = args[++i];
+            } else if (collator.compare(flags, "-cacerts") == 0) {
+                cacerts = true;
             } else if (collator.compare(flags, "-storepass") == 0 ||
                     collator.compare(flags, "-deststorepass") == 0) {
                 storePass = getPass(modifier, args[++i]);
@@ -636,6 +640,15 @@
      * Execute the commands.
      */
     void doCommands(PrintStream out) throws Exception {
+
+        if (cacerts) {
+            if (ksfname != null || storetype != null) {
+                throw new IllegalArgumentException(rb.getString
+                        ("the.keystore.or.storetype.option.cannot.be.used.with.the.cacerts.option"));
+            }
+            ksfname = KeyStoreUtil.getCacerts();
+        }
+
         if (storetype == null) {
             storetype = KeyStore.getDefaultType();
         }
--- a/jdk/src/java.base/share/classes/sun/security/tools/keytool/Resources.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/src/java.base/share/classes/sun/security/tools/keytool/Resources.java	Wed Jul 05 22:05:22 2017 +0200
@@ -127,6 +127,10 @@
                 "key bit size"}, //-keysize
         {"keystore.name",
                 "keystore name"}, //-keystore
+        {"access.the.cacerts.keystore",
+                "access the cacerts keystore"}, // -cacerts
+        {"warning.cacerts.option",
+                "Warning: use -cacerts option to access cacerts keystore"},
         {"new.password",
                 "new password"}, //-new
         {"do.not.prompt",
@@ -194,6 +198,8 @@
         {"Command.option.flag.needs.an.argument.", "Command option {0} needs an argument."},
         {"Warning.Different.store.and.key.passwords.not.supported.for.PKCS12.KeyStores.Ignoring.user.specified.command.value.",
                 "Warning:  Different store and key passwords not supported for PKCS12 KeyStores. Ignoring user-specified {0} value."},
+        {"the.keystore.or.storetype.option.cannot.be.used.with.the.cacerts.option",
+            "The -keystore or -storetype option cannot be used with the -cacerts option"},
         {".keystore.must.be.NONE.if.storetype.is.{0}",
                 "-keystore must be NONE if -storetype is {0}"},
         {"Too.many.retries.program.terminated",
Binary file jdk/src/java.base/share/conf/security/cacerts has changed
Binary file jdk/src/java.base/share/lib/security/cacerts has changed
--- a/jdk/src/java.base/share/native/libjli/args.c	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/src/java.base/share/native/libjli/args.c	Wed Jul 05 22:05:22 2017 +0200
@@ -102,24 +102,21 @@
 
     // All arguments arrive here must be a launcher argument,
     // ie. by now, all argfile expansions must have been performed.
-    if (*arg++ == '-') {
+    if (*arg == '-') {
         expectingNoDashArg = JNI_FALSE;
-        if (JLI_StrCmp(arg, "cp") == 0 ||
-            JLI_StrCmp(arg, "classpath") == 0 ||
-            JLI_StrCmp(arg, "addmods") == 0 ||
-            JLI_StrCmp(arg, "limitmods") == 0 ||
-            JLI_StrCmp(arg, "mp") == 0 ||
-            JLI_StrCmp(arg, "modulepath") == 0 ||
-            JLI_StrCmp(arg, "upgrademodulepath") == 0) {
+        if (IsWhiteSpaceOption(arg)) {
+            // expect an argument
             expectingNoDashArg = JNI_TRUE;
-        } else if (JLI_StrCmp(arg, "jar") == 0 ||
-                   JLI_StrCmp(arg, "m") == 0) {
-            // This is tricky, we do expect NoDashArg
-            // But that is considered main class to stop expansion
-            expectingNoDashArg = JNI_FALSE;
-            // We can not just update the idx here because if -jar @file
-            // still need expansion of @file to get the argument for -jar
-        } else if (JLI_StrCmp(arg, "Xdisable-@files") == 0) {
+
+            if (JLI_StrCmp(arg, "-jar") == 0 ||
+                JLI_StrCmp(arg, "-m") == 0) {
+                // This is tricky, we do expect NoDashArg
+                // But that is considered main class to stop expansion
+                expectingNoDashArg = JNI_FALSE;
+                // We can not just update the idx here because if -jar @file
+                // still need expansion of @file to get the argument for -jar
+            }
+        } else if (JLI_StrCmp(arg, "-Xdisable-@files") == 0) {
             stopExpansion = JNI_TRUE;
         }
     } else {
--- a/jdk/src/java.base/share/native/libjli/java.c	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/src/java.base/share/native/libjli/java.c	Wed Jul 05 22:05:22 2017 +0200
@@ -69,7 +69,7 @@
 static jboolean printUsage = JNI_FALSE;   /* print and exit*/
 static jboolean printXUsage = JNI_FALSE;  /* print and exit*/
 static jboolean dryRun = JNI_FALSE;       /* initialize VM and exit */
-static char     *showSettings = NULL;      /* print but continue */
+static char     *showSettings = NULL;     /* print but continue */
 static char     *listModules = NULL;
 
 static const char *_program_name;
@@ -99,17 +99,9 @@
  * Prototypes for functions internal to launcher.
  */
 static void SetClassPath(const char *s);
-static void SetModulePath(const char *s);
-static void SetUpgradeModulePath(const char *s);
 static void SetMainModule(const char *s);
-static void SetAddModulesProp(const char *mods);
-static void SetLimitModulesProp(const char *mods);
-static void SetAddReadsProp(const jint n, const char *s);
-static void SetAddExportsProp(const jint n, const char *s);
-static void SetPatchProp(const jint n, const char *s);
 static void SelectVersion(int argc, char **argv, char **main_class);
 static void SetJvmEnvironment(int argc, char **argv);
-static jboolean IsWhiteSpaceOptionArgument(const char* name);
 static jboolean ParseArguments(int *pargc, char ***pargv,
                                int *pmode, char **pwhat,
                                int *pret, const char *jrepath);
@@ -133,6 +125,18 @@
 static void DumpState();
 static jboolean RemovableOption(char *option);
 
+enum OptionKind {
+    LAUNCHER_OPTION = 0,
+    LAUNCHER_OPTION_WITH_ARGUMENT,
+    LAUNCHER_MAIN_OPTION,
+    VM_LONG_OPTION,
+    VM_LONG_OPTION_WITH_ARGUMENT,
+    VM_OPTION
+};
+
+static int GetOpt(int *pargc, char ***pargv, char **poption, char **pvalue);
+static jboolean IsOptionWithArgument(int argc, char **argv);
+
 /* Maximum supported entries from jvm.cfg. */
 #define INIT_MAX_KNOWN_VMS      10
 
@@ -162,6 +166,19 @@
 static void FreeKnownVMs();
 static jboolean IsWildCardEnabled();
 
+/*
+ * This reports error.  VM will not be created and no usage is printed.
+ */
+#define REPORT_ERROR(AC_ok, AC_failure_message, AC_questionable_arg) \
+    do { \
+        if (!AC_ok) { \
+            JLI_ReportErrorMessage(AC_failure_message, AC_questionable_arg); \
+            printUsage = JNI_FALSE; \
+            *pret = 1; \
+            return JNI_FALSE; \
+        } \
+    } while (JNI_FALSE)
+
 #define ARG_CHECK(AC_arg_count, AC_failure_message, AC_questionable_arg) \
     do { \
         if (AC_arg_count < 1) { \
@@ -511,17 +528,73 @@
 }
 
 /*
- * Test if the given option name has a whitespace separated argument.
+ * Test if the given name is one of the class path options.
  */
-jboolean
-IsWhiteSpaceOptionArgument(const char* name) {
+static jboolean
+IsClassPathOption(const char* name) {
     return JLI_StrCmp(name, "-classpath") == 0 ||
            JLI_StrCmp(name, "-cp") == 0 ||
-           JLI_StrCmp(name, "-modulepath") == 0 ||
-           JLI_StrCmp(name, "-mp") == 0 ||
-           JLI_StrCmp(name, "-upgrademodulepath") == 0 ||
-           JLI_StrCmp(name, "-addmods") == 0 ||
-           JLI_StrCmp(name, "-limitmods") == 0;
+           JLI_StrCmp(name, "--class-path") == 0;
+}
+
+/*
+ * Test if the given name is a launcher option taking the main entry point.
+ */
+static jboolean
+IsLauncherMainOption(const char* name) {
+    return JLI_StrCmp(name, "--module") == 0 ||
+           JLI_StrCmp(name, "-m") == 0;
+}
+
+/*
+ * Test if the given name is a white-space launcher option.
+ */
+static jboolean
+IsLauncherOption(const char* name) {
+    return IsClassPathOption(name) ||
+           IsLauncherMainOption(name) ||
+           JLI_StrCmp(name, "--list-modules") == 0;
+}
+
+#ifndef OLD_MODULE_OPTIONS
+/*
+ * Old module options for transition
+ */
+static jboolean
+IsOldModuleOption(const char* name) {
+    return JLI_StrCmp(name, "-modulepath") == 0 ||
+    JLI_StrCmp(name, "-mp") == 0 ||
+    JLI_StrCmp(name, "-upgrademodulepath") == 0 ||
+    JLI_StrCmp(name, "-addmods") == 0 ||
+    JLI_StrCmp(name, "-limitmods") == 0;
+}
+#endif
+
+/*
+ * Test if the given name is a module-system white-space option that
+ * will be passed to the VM with its corresponding long-form option
+ * name and "=" delimiter.
+ */
+static jboolean
+IsModuleOption(const char* name) {
+    return JLI_StrCmp(name, "--module-path") == 0 ||
+           JLI_StrCmp(name, "-p") == 0 ||
+           JLI_StrCmp(name, "--upgrade-module-path") == 0 ||
+           JLI_StrCmp(name, "--add-modules") == 0 ||
+           JLI_StrCmp(name, "--limit-modules") == 0 ||
+           JLI_StrCmp(name, "--add-exports") == 0 ||
+           JLI_StrCmp(name, "--add-reads") == 0 ||
+           JLI_StrCmp(name, "--patch-module") == 0 ||
+           IsOldModuleOption(name);
+}
+
+/*
+ * Test if the given name has a white space option.
+ */
+jboolean
+IsWhiteSpaceOption(const char* name) {
+    return IsModuleOption(name) ||
+           IsLauncherOption(name);
 }
 
 /*
@@ -559,7 +632,7 @@
                 continue;
             }
         } else {
-            if (IsWhiteSpaceOptionArgument(arg)) {
+            if (IsWhiteSpaceOption(arg)) {
                 newArgv[newArgvIdx++] = arg;
                 argi++;
                 if (argi < argc) {
@@ -701,7 +774,7 @@
         if (i > 0) {
             char *prev = argv[i - 1];
             // skip non-dash arg preceded by class path specifiers
-            if (*arg != '-' && IsWhiteSpaceOptionArgument(prev)) {
+            if (*arg != '-' && IsWhiteSpaceOption(prev)) {
                 continue;
             }
 
@@ -709,6 +782,7 @@
                     || JLI_StrCmp(arg, "-version") == 0
                     || JLI_StrCmp(arg, "-fullversion") == 0
                     || JLI_StrCmp(arg, "-help") == 0
+                    || JLI_StrCmp(arg, "--help") == 0
                     || JLI_StrCmp(arg, "-?") == 0
                     || JLI_StrCmp(arg, "-jar") == 0
                     || JLI_StrCmp(arg, "-X") == 0) {
@@ -882,39 +956,16 @@
 }
 
 static void
-SetModulePath(const char *s)
+AddLongFormOption(const char *option, const char *arg)
 {
+    static const char format[] = "%s=%s";
     char *def;
-    const char *orig = s;
-    static const char format[] = "-Djdk.module.path=%s";
-    if (s == NULL)
-        return;
-    s = JLI_WildcardExpandClasspath(s);
-    def = JLI_MemAlloc(sizeof(format)
-                       - 2 /* strlen("%s") */
-                       + JLI_StrLen(s));
-    sprintf(def, format, s);
-    AddOption(def, NULL);
-    if (s != orig)
-        JLI_MemFree((char *) s);
-}
+    size_t def_len;
 
-static void
-SetUpgradeModulePath(const char *s)
-{
-    char *def;
-    const char *orig = s;
-    static const char format[] = "-Djdk.upgrade.module.path=%s";
-    if (s == NULL)
-        return;
-    s = JLI_WildcardExpandClasspath(s);
-    def = JLI_MemAlloc(sizeof(format)
-                       - 2 /* strlen("%s") */
-                       + JLI_StrLen(s));
-    sprintf(def, format, s);
+    def_len = JLI_StrLen(option) + 1 + JLI_StrLen(arg) + 1;
+    def = JLI_MemAlloc(def_len);
+    JLI_Snprintf(def, def_len, format, option, arg);
     AddOption(def, NULL);
-    if (s != orig)
-        JLI_MemFree((char *) s);
 }
 
 static void
@@ -939,46 +990,6 @@
     AddOption(def, NULL);
 }
 
-static void
-SetAddModulesProp(const char *mods) {
-    size_t buflen = JLI_StrLen(mods) + 40;
-    char *prop = (char *)JLI_MemAlloc(buflen);
-    JLI_Snprintf(prop, buflen, "-Djdk.launcher.addmods=%s", mods);
-    AddOption(prop, NULL);
-}
-
-static void
-SetLimitModulesProp(const char *mods) {
-    size_t buflen = JLI_StrLen(mods) + 40;
-    char *prop = (char *)JLI_MemAlloc(buflen);
-    JLI_Snprintf(prop, buflen, "-Djdk.launcher.limitmods=%s", mods);
-    AddOption(prop, NULL);
-}
-
-static void
-SetAddReadsProp(const jint n, const char *s) {
-    size_t buflen = JLI_StrLen(s) + 40;
-    char *prop = (char *)JLI_MemAlloc(buflen);
-    JLI_Snprintf(prop, buflen, "-Djdk.launcher.addreads.%d=%s", n, s);
-    AddOption(prop, NULL);
-}
-
-static void
-SetAddExportsProp(const jint n, const char *s) {
-    size_t buflen = JLI_StrLen(s) + 40;
-    char *prop = (char *)JLI_MemAlloc(buflen);
-    JLI_Snprintf(prop, buflen, "-Djdk.launcher.addexports.%d=%s", n, s);
-    AddOption(prop, NULL);
-}
-
-static void
-SetPatchProp(const jint n, const char *s) {
-    size_t buflen = JLI_StrLen(s) + 40;
-    char *prop = (char *)JLI_MemAlloc(buflen);
-    JLI_Snprintf(prop, buflen, "-Djdk.launcher.patch.%d=%s", n, s);
-    AddOption(prop, NULL);
-}
-
 /*
  * The SelectVersion() routine ensures that an appropriate version of
  * the JRE is running.  The specification for the appropriate version
@@ -1003,6 +1014,7 @@
     char    *splash_jar_name = NULL;
     char    *env_in;
     int     res;
+    jboolean has_arg;
 
     /*
      * If the version has already been selected, set *main_class
@@ -1033,9 +1045,11 @@
      * This capability is no longer available with JRE versions 1.9 and later.
      * These command line options are reported as errors.
      */
+
     argc--;
     argv++;
     while ((arg = *argv) != 0 && *arg == '-') {
+        has_arg = IsOptionWithArgument(argc, argv);
         if (JLI_StrCCmp(arg, "-version:") == 0) {
             JLI_ReportErrorMessage(SPC_ERROR1);
         } else if (JLI_StrCmp(arg, "-jre-restrict-search") == 0) {
@@ -1045,10 +1059,12 @@
         } else {
             if (JLI_StrCmp(arg, "-jar") == 0)
                 jarflag = 1;
-            if (IsWhiteSpaceOptionArgument(arg) && (argc >= 2)) {
-                argc--;
-                argv++;
-                arg = *argv;
+            if (IsWhiteSpaceOption(arg)) {
+                if (has_arg) {
+                    argc--;
+                    argv++;
+                    arg = *argv;
+                }
             }
 
             /*
@@ -1140,6 +1156,108 @@
 }
 
 /*
+ * Test if the current argv is an option, i.e. with a leading `-`
+ * and followed with an argument without a leading `-`.
+ */
+static jboolean
+IsOptionWithArgument(int argc, char** argv) {
+    char* option;
+    char* arg;
+
+    if (argc <= 1)
+        return JNI_FALSE;
+
+    option = *argv;
+    arg = *(argv+1);
+    return *option == '-' && *arg != '-';
+}
+
+/*
+ * Gets the option, and its argument if the option has an argument.
+ * It will update *pargc, **pargv to the next option.
+ */
+static int
+GetOpt(int *pargc, char ***pargv, char **poption, char **pvalue) {
+    int argc = *pargc;
+    char** argv = *pargv;
+    char* arg = *argv;
+
+    char* option = arg;
+    char* value = NULL;
+    char* equals = NULL;
+    int kind = LAUNCHER_OPTION;
+    jboolean has_arg = JNI_FALSE;
+
+    // check if this option may be a white-space option with an argument
+    has_arg = IsOptionWithArgument(argc, argv);
+
+    argv++; --argc;
+    if (IsLauncherOption(arg)) {
+        if (has_arg) {
+            value = *argv;
+            argv++; --argc;
+        }
+        kind = IsLauncherMainOption(arg) ? LAUNCHER_MAIN_OPTION
+                                         : LAUNCHER_OPTION_WITH_ARGUMENT;
+    } else if (IsModuleOption(arg)) {
+        kind = VM_LONG_OPTION_WITH_ARGUMENT;
+        if (has_arg) {
+            value = *argv;
+            argv++; --argc;
+        }
+
+        /*
+         * Support short form alias
+         */
+        if (JLI_StrCmp(arg, "-p") == 0) {
+            option = "--module-path";
+        }
+
+    } else if (JLI_StrCCmp(arg, "--") == 0 && (equals = JLI_StrChr(arg, '=')) != NULL) {
+        value = equals+1;
+        if (JLI_StrCCmp(arg, "--list-modules=") == 0 ||
+            JLI_StrCCmp(arg, "--module=") == 0 ||
+            JLI_StrCCmp(arg, "--class-path=") == 0) {
+            kind = LAUNCHER_OPTION_WITH_ARGUMENT;
+        } else {
+            kind = VM_LONG_OPTION;
+        }
+    }
+
+#ifndef OLD_MODULE_OPTIONS
+    // for transition to support both old and new syntax
+    if (JLI_StrCmp(arg, "-modulepath") == 0 ||
+        JLI_StrCmp(arg, "-mp") == 0) {
+        option = "--module-path";
+    } else if (JLI_StrCmp(arg, "-upgrademodulepath") == 0) {
+        option = "--upgrade-module-path";
+    } else if (JLI_StrCmp(arg, "-addmods") == 0) {
+        option = "--add-modules";
+    } else if (JLI_StrCmp(arg, "-limitmods") == 0) {
+        option = "--limit-modules";
+    } else if (JLI_StrCCmp(arg, "-XaddExports:") == 0) {
+        option = "--add-exports";
+        value = arg + 13;
+        kind = VM_LONG_OPTION_WITH_ARGUMENT;
+    } else if (JLI_StrCCmp(arg, "-XaddReads:") == 0) {
+        option = "--add-reads";
+        value = arg + 11;
+        kind = VM_LONG_OPTION_WITH_ARGUMENT;
+    } else if (JLI_StrCCmp(arg, "-Xpatch:") == 0) {
+        option = "--patch-module";
+        value = arg + 8;
+        kind = VM_LONG_OPTION_WITH_ARGUMENT;
+    }
+#endif
+
+    *pargc = argc;
+    *pargv = argv;
+    *poption = option;
+    *pvalue = value;
+    return kind;
+}
+
+/*
  * Parses command line arguments.  Returns JNI_FALSE if launcher
  * should exit without starting vm, returns JNI_TRUE if vm needs
  * to be started to process given options.  *pret (the launcher
@@ -1158,52 +1276,85 @@
     *pret = 0;
 
     while ((arg = *argv) != 0 && *arg == '-') {
-        argv++; --argc;
-        if (JLI_StrCmp(arg, "-classpath") == 0 || JLI_StrCmp(arg, "-cp") == 0) {
-            ARG_CHECK (argc, ARG_ERROR1, arg);
-            SetClassPath(*argv);
-            mode = LM_CLASS;
-            argv++; --argc;
-        } else if (JLI_StrCmp(arg, "-modulepath") == 0 || JLI_StrCmp(arg, "-mp") == 0) {
-            ARG_CHECK (argc, ARG_ERROR4, arg);
-            SetModulePath(*argv);
-            argv++; --argc;
-        } else if (JLI_StrCmp(arg, "-upgrademodulepath") == 0) {
-            ARG_CHECK (argc, ARG_ERROR4, arg);
-            SetUpgradeModulePath(*argv);
-            argv++; --argc;
-        } else if (JLI_StrCmp(arg, "-jar") == 0) {
-            ARG_CHECK (argc, ARG_ERROR2, arg);
+        char *option = NULL;
+        char *value = NULL;
+        int kind = GetOpt(&argc, &argv, &option, &value);
+        jboolean has_arg = value != NULL;
+
+/*
+ * Option to set main entry point
+ */
+        if (JLI_StrCmp(arg, "-jar") == 0) {
+            ARG_CHECK(argc, ARG_ERROR2, arg);
             mode = LM_JAR;
-        } else if (JLI_StrCmp(arg, "-m") == 0) {
-            ARG_CHECK (argc, ARG_ERROR5, arg);
-            SetMainModule(*argv);
+        } else if (JLI_StrCmp(arg, "--module") == 0 ||
+                   JLI_StrCCmp(arg, "--module=") == 0 ||
+                   JLI_StrCmp(arg, "-m") == 0) {
+            REPORT_ERROR (has_arg, ARG_ERROR5, arg);
+            SetMainModule(value);
             mode = LM_MODULE;
-        } else if (JLI_StrCmp(arg, "-addmods") == 0) {
-            ARG_CHECK (argc, ARG_ERROR6, arg);
-            SetAddModulesProp(*argv);
-            argv++; --argc;
-        } else if (JLI_StrCmp(arg, "-limitmods") == 0) {
-            ARG_CHECK (argc, ARG_ERROR6, arg);
-            SetLimitModulesProp(*argv);
-            argv++; --argc;
-        } else if (JLI_StrCmp(arg, "-listmods") == 0 ||
-                   JLI_StrCCmp(arg, "-listmods:") == 0) {
+            if (has_arg) {
+               *pwhat = value;
+                break;
+            }
+        } else if (JLI_StrCmp(arg, "--class-path") == 0 ||
+                   JLI_StrCCmp(arg, "--class-path=") == 0 ||
+                   JLI_StrCmp(arg, "-classpath") == 0 ||
+                   JLI_StrCmp(arg, "-cp") == 0) {
+            REPORT_ERROR (has_arg, ARG_ERROR1, arg);
+            SetClassPath(value);
+            mode = LM_CLASS;
+        } else if (JLI_StrCmp(arg, "--list-modules") == 0 ||
+                   JLI_StrCCmp(arg, "--list-modules=") == 0) {
             listModules = arg;
+
+            // set listModules to --list-modules=<module-names> if argument is specified
+            if (JLI_StrCmp(arg, "--list-modules") == 0 && has_arg) {
+                static const char format[] = "%s=%s";
+                size_t buflen = JLI_StrLen(option) + 2 + JLI_StrLen(value);
+                listModules = JLI_MemAlloc(buflen);
+                JLI_Snprintf(listModules, buflen, format, option, value);
+            }
             return JNI_TRUE;
-        } else if (JLI_StrCCmp(arg, "-XaddReads:") == 0) {
-            static jint n;
-            char *value = arg + 11;
-            SetAddReadsProp(n++, value);
-        } else if (JLI_StrCCmp(arg, "-XaddExports:") == 0) {
-            static jint n;
-            char *value = arg + 13;
-            SetAddExportsProp(n++, value);
-        } else if (JLI_StrCCmp(arg, "-Xpatch:") == 0) {
-            static jint n;
-            char *value = arg + 8;
-            SetPatchProp(n++, value);
-        } else if (JLI_StrCmp(arg, "-help") == 0 ||
+/*
+ * Parse white-space options
+ */
+        } else if (has_arg) {
+            if (kind == VM_LONG_OPTION) {
+                AddOption(option, NULL);
+            } else if (kind == VM_LONG_OPTION_WITH_ARGUMENT) {
+                AddLongFormOption(option, value);
+            }
+/*
+ * Error missing argument
+ */
+        } else if (!has_arg && IsWhiteSpaceOption(arg)) {
+            if (JLI_StrCmp(arg, "--module-path") == 0 ||
+                JLI_StrCmp(arg, "-p") == 0 ||
+                JLI_StrCmp(arg, "--upgrade-module-path") == 0) {
+                REPORT_ERROR (has_arg, ARG_ERROR4, arg);
+            } else if (JLI_StrCmp(arg, "--add-modules") == 0 ||
+                       JLI_StrCmp(arg, "--limit-modules") == 0 ||
+                       JLI_StrCmp(arg, "--add-exports") == 0 ||
+                       JLI_StrCmp(arg, "--add-reads") == 0 ||
+                       JLI_StrCmp(arg, "--patch-module") == 0) {
+                REPORT_ERROR (has_arg, ARG_ERROR6, arg);
+            }
+#ifndef OLD_MODULE_OPTIONS
+            else if (JLI_StrCmp(arg, "-modulepath") == 0 ||
+                     JLI_StrCmp(arg, "-mp") == 0 ||
+                     JLI_StrCmp(arg, "-upgrademodulepath") == 0) {
+                REPORT_ERROR (has_arg, ARG_ERROR4, arg);
+            } else if (JLI_StrCmp(arg, "-addmods") == 0 ||
+                       JLI_StrCmp(arg, "-limitmods") == 0) {
+                REPORT_ERROR (has_arg, ARG_ERROR6, arg);
+            }
+#endif
+/*
+ * The following cases will cause the argument parsing to stop
+ */
+        } else if (JLI_StrCmp(arg, "--help") == 0 ||
+                   JLI_StrCmp(arg, "-help") == 0 ||
                    JLI_StrCmp(arg, "-h") == 0 ||
                    JLI_StrCmp(arg, "-?") == 0) {
             printUsage = JNI_TRUE;
@@ -1282,7 +1433,7 @@
         }
     }
 
-    if (--argc >= 0) {
+    if (*pwhat == NULL && --argc >= 0) {
         *pwhat = *argv++;
     }
 
@@ -1692,7 +1843,7 @@
 ListModules(JNIEnv *env, char *optString)
 {
     jmethodID listModulesID;
-    jstring joptString;
+    jstring joptString = NULL;
     jclass cls = GetLauncherHelperClass(env);
     NULL_CHECK(cls);
     NULL_CHECK(listModulesID = (*env)->GetStaticMethodID(env, cls,
--- a/jdk/src/java.base/share/native/libjli/java.h	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/src/java.base/share/native/libjli/java.h	Wed Jul 05 22:05:22 2017 +0200
@@ -161,6 +161,7 @@
 jint ReadKnownVMs(const char *jvmcfg, jboolean speculative);
 char *CheckJvmType(int *argc, char ***argv, jboolean speculative);
 void AddOption(char *str, void *info);
+jboolean IsWhiteSpaceOption(const char* name);
 
 enum ergo_policy {
    DEFAULT_POLICY = 0,
--- a/jdk/src/java.base/windows/lib/security/default.policy	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/src/java.base/windows/lib/security/default.policy	Wed Jul 05 22:05:22 2017 +0200
@@ -11,5 +11,6 @@
                    "clearProviderProperties.SunMSCAPI";
     permission java.security.SecurityPermission
                    "removeProviderProperty.SunMSCAPI";
+    permission java.security.SecurityPermission "authProvider.SunMSCAPI";
     permission java.util.PropertyPermission "*", "read";
 };
--- a/jdk/src/java.desktop/unix/native/common/awt/systemscale/systemScale.h	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/src/java.desktop/unix/native/common/awt/systemscale/systemScale.h	Wed Jul 05 22:05:22 2017 +0200
@@ -26,7 +26,7 @@
 #include <signal.h>
 #include <stdlib.h>
 
-double getNativeScaleFactor();
+double getNativeScaleFactor(char *output_name);
 
 #endif
 
--- a/jdk/src/java.desktop/unix/native/libsplashscreen/splashscreen_sys.c	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/src/java.desktop/unix/native/libsplashscreen/splashscreen_sys.c	Wed Jul 05 22:05:22 2017 +0200
@@ -806,7 +806,7 @@
 #ifndef __linux__
     return JNI_FALSE;
 #endif
-    *scaleFactor = getNativeScaleFactor();
+    *scaleFactor = getNativeScaleFactor(NULL);
     if (*scaleFactor == 2.0) {
         size_t length = 0;
         char *stringToAppend = ".java-scale2x";
--- a/jdk/src/java.httpclient/share/classes/java/net/http/RawChannel.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/src/java.httpclient/share/classes/java/net/http/RawChannel.java	Wed Jul 05 22:05:22 2017 +0200
@@ -31,7 +31,7 @@
 /*
  * I/O abstraction used to implement WebSocket.
  */
-public interface RawChannel {
+interface RawChannel {
 
     interface RawEvent {
 
--- a/jdk/src/java.security.jgss/share/classes/sun/security/jgss/krb5/Krb5InitCredential.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/src/java.security.jgss/share/classes/sun/security/jgss/krb5/Krb5InitCredential.java	Wed Jul 05 22:05:22 2017 +0200
@@ -235,8 +235,11 @@
      */
     public int getInitLifetime() throws GSSException {
         int retVal = 0;
-        retVal = (int)(getEndTime().getTime()
-                       - (new Date().getTime()));
+        Date d = getEndTime();
+        if (d == null) {
+            return 0;
+        }
+        retVal = (int)(d.getTime() - (new Date().getTime()));
 
         return retVal/1000;
     }
--- a/jdk/src/java.smartcardio/share/classes/javax/smartcardio/CardPermission.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/src/java.smartcardio/share/classes/javax/smartcardio/CardPermission.java	Wed Jul 05 22:05:22 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -118,7 +118,7 @@
     /**
      * @serial
      */
-    private volatile String actions;
+    private final String actions;
 
     /**
      * Constructs a new CardPermission with the specified actions.
@@ -143,10 +143,14 @@
             throw new NullPointerException();
         }
         mask = getMask(actions);
+        this.actions = getActions(mask);
     }
 
     private static int getMask(String actions) {
-        if ((actions == null) || (actions.length() == 0)) {
+        if (actions == null) {
+            return 0;
+        }
+        if (actions.length() == 0) {
             throw new IllegalArgumentException("actions must not be empty");
         }
 
@@ -177,6 +181,9 @@
     }
 
     private static String getActions(int mask) {
+        if (mask == 0) {
+            return null;
+        }
         if (mask == A_ALL) {
             return S_ALL;
         }
@@ -200,9 +207,6 @@
      * @return the canonical string representation of the actions.
      */
     public String getActions() {
-        if (actions == null) {
-            actions = getActions(mask);
-        }
         return actions;
     }
 
@@ -278,10 +282,6 @@
 
     private void writeObject(ObjectOutputStream s) throws IOException {
         // Write out the actions. The superclass takes care of the name.
-        // Call getActions to make sure actions field is initialized
-        if (actions == null) {
-            getActions();
-        }
         s.defaultWriteObject();
     }
 
@@ -291,5 +291,4 @@
         s.defaultReadObject();
         mask = getMask(actions);
     }
-
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/jdk.jartool/share/classes/sun/tools/jar/FingerPrint.java	Wed Jul 05 22:05:22 2017 +0200
@@ -0,0 +1,324 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package sun.tools.jar;
+
+import jdk.internal.org.objectweb.asm.*;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * A FingerPrint is an abstract representation of a JarFile entry that contains
+ * information to determine if the entry represents a class or a
+ * resource, and whether two entries are identical.  If the FingerPrint represents
+ * a class, it also contains information to (1) describe the public API;
+ * (2) compare the public API of this class with another class;  (3) determine
+ * whether or not it's a nested class and, if so, the name of the associated
+ * top level class; and (4) for an canonically ordered set of classes determine
+ * if the class versions are compatible.  A set of classes is canonically
+ * ordered if the classes in the set have the same name, and the base class
+ * precedes the versioned classes and if each versioned class with version
+ * {@code n} precedes classes with versions {@code > n} for all versions
+ * {@code n}.
+ */
+final class FingerPrint {
+    private static final MessageDigest MD;
+
+    private final byte[] sha1;
+    private final ClassAttributes attrs;
+    private final boolean isClassEntry;
+    private final String entryName;
+
+    static {
+        try {
+            MD = MessageDigest.getInstance("SHA-1");
+        } catch (NoSuchAlgorithmException x) {
+            // log big problem?
+            throw new RuntimeException(x);
+        }
+    }
+
+    public FingerPrint(String entryName,byte[] bytes) throws IOException {
+        this.entryName = entryName;
+        if (entryName.endsWith(".class") && isCafeBabe(bytes)) {
+            isClassEntry = true;
+            sha1 = sha1(bytes, 8);  // skip magic number and major/minor version
+            attrs = getClassAttributes(bytes);
+        } else {
+            isClassEntry = false;
+            sha1 = sha1(bytes);
+            attrs = new ClassAttributes();   // empty class
+        }
+    }
+
+    public boolean isClass() {
+        return isClassEntry;
+    }
+
+    public boolean isNestedClass() {
+        return attrs.nestedClass;
+    }
+
+    public boolean isPublicClass() {
+        return attrs.publicClass;
+    }
+
+    public boolean isIdentical(FingerPrint that) {
+        if (that == null) return false;
+        if (this == that) return true;
+        return isEqual(this.sha1, that.sha1);
+    }
+
+    public boolean isCompatibleVersion(FingerPrint that) {
+        return attrs.version >= that.attrs.version;
+    }
+
+    public boolean isSameAPI(FingerPrint that) {
+        if (that == null) return false;
+        return attrs.equals(that.attrs);
+    }
+
+    public String name() {
+        String name = attrs.name;
+        return name == null ? entryName : name;
+    }
+
+    public String topLevelName() {
+        String name = attrs.topLevelName;
+        return name == null ? name() : name;
+    }
+
+    private byte[] sha1(byte[] entry) {
+        MD.update(entry);
+        return MD.digest();
+    }
+
+    private byte[] sha1(byte[] entry, int offset) {
+        MD.update(entry, offset, entry.length - offset);
+        return MD.digest();
+    }
+
+    private boolean isEqual(byte[] sha1_1, byte[] sha1_2) {
+        return MessageDigest.isEqual(sha1_1, sha1_2);
+    }
+
+    private static final byte[] cafeBabe = {(byte)0xca, (byte)0xfe, (byte)0xba, (byte)0xbe};
+
+    private boolean isCafeBabe(byte[] bytes) {
+        if (bytes.length < 4) return false;
+        for (int i = 0; i < 4; i++) {
+            if (bytes[i] != cafeBabe[i]) {
+                return false;
+            }
+        }
+        return true;
+    }
+
+    private ClassAttributes getClassAttributes(byte[] bytes) {
+        ClassReader rdr = new ClassReader(bytes);
+        ClassAttributes attrs = new ClassAttributes();
+        rdr.accept(attrs, 0);
+        return attrs;
+    }
+
+    private static final class Field {
+        private final int access;
+        private final String name;
+        private final String desc;
+
+        Field(int access, String name, String desc) {
+            this.access = access;
+            this.name = name;
+            this.desc = desc;
+        }
+
+        @Override
+        public boolean equals(Object that) {
+            if (that == null) return false;
+            if (this == that) return true;
+            if (!(that instanceof Field)) return false;
+            Field field = (Field)that;
+            return (access == field.access) && name.equals(field.name)
+                    && desc.equals(field.desc);
+        }
+
+        @Override
+        public int hashCode() {
+            int result = 17;
+            result = 37 * result + access;
+            result = 37 * result + name.hashCode();
+            result = 37 * result + desc.hashCode();
+            return result;
+        }
+    }
+
+    private static final class Method {
+        private final int access;
+        private final String name;
+        private final String desc;
+        private final Set<String> exceptions;
+
+        Method(int access, String name, String desc, Set<String> exceptions) {
+            this.access = access;
+            this.name = name;
+            this.desc = desc;
+            this.exceptions = exceptions;
+        }
+
+        @Override
+        public boolean equals(Object that) {
+            if (that == null) return false;
+            if (this == that) return true;
+            if (!(that instanceof Method)) return false;
+            Method method = (Method)that;
+            return (access == method.access) && name.equals(method.name)
+                    && desc.equals(method.desc)
+                    && exceptions.equals(method.exceptions);
+        }
+
+        @Override
+        public int hashCode() {
+            int result = 17;
+            result = 37 * result + access;
+            result = 37 * result + name.hashCode();
+            result = 37 * result + desc.hashCode();
+            result = 37 * result + exceptions.hashCode();
+            return result;
+        }
+    }
+
+    private static final class ClassAttributes extends ClassVisitor {
+        private String name;
+        private String topLevelName;
+        private String superName;
+        private int version;
+        private int access;
+        private boolean publicClass;
+        private boolean nestedClass;
+        private final Set<Field> fields = new HashSet<>();
+        private final Set<Method> methods = new HashSet<>();
+
+        public ClassAttributes() {
+            super(Opcodes.ASM5);
+        }
+
+        private boolean isPublic(int access) {
+            return ((access & Opcodes.ACC_PUBLIC) == Opcodes.ACC_PUBLIC)
+                    || ((access & Opcodes.ACC_PROTECTED) == Opcodes.ACC_PROTECTED);
+        }
+
+        @Override
+        public void visit(int version, int access, String name, String signature,
+                          String superName, String[] interfaces) {
+            this.version = version;
+            this.access = access;
+            this.name = name;
+            this.nestedClass = name.contains("$");
+            this.superName = superName;
+            this.publicClass = isPublic(access);
+        }
+
+        @Override
+        public void visitOuterClass(String owner, String name, String desc) {
+            if (!this.nestedClass) return;
+            this.topLevelName = owner;
+        }
+
+        @Override
+        public void visitInnerClass(String name, String outerName, String innerName,
+                                    int access) {
+            if (!this.nestedClass) return;
+            if (outerName == null) return;
+            if (!this.name.equals(name)) return;
+            if (this.topLevelName == null) this.topLevelName = outerName;
+        }
+
+        @Override
+        public FieldVisitor visitField(int access, String name, String desc,
+                                       String signature, Object value) {
+            if (isPublic(access)) {
+                fields.add(new Field(access, name, desc));
+            }
+            return null;
+        }
+
+        @Override
+        public MethodVisitor visitMethod(int access, String name, String desc,
+                                         String signature, String[] exceptions) {
+            if (isPublic(access)) {
+                Set<String> exceptionSet = new HashSet<>();
+                if (exceptions != null) {
+                    for (String e : exceptions) {
+                        exceptionSet.add(e);
+                    }
+                }
+                // treat type descriptor as a proxy for signature because signature
+                // is usually null, need to strip off the return type though
+                int n;
+                if (desc != null && (n = desc.lastIndexOf(')')) != -1) {
+                    desc = desc.substring(0, n + 1);
+                    methods.add(new Method(access, name, desc, exceptionSet));
+                }
+            }
+            return null;
+        }
+
+        @Override
+        public void visitEnd() {
+            this.nestedClass = this.topLevelName != null;
+        }
+
+        @Override
+        public boolean equals(Object that) {
+            if (that == null) return false;
+            if (this == that) return true;
+            if (!(that instanceof ClassAttributes)) return false;
+            ClassAttributes clsAttrs = (ClassAttributes)that;
+            boolean superNameOkay = superName != null
+                    ? superName.equals(clsAttrs.superName) : true;
+            return access == clsAttrs.access
+                    && superNameOkay
+                    && fields.equals(clsAttrs.fields)
+                    && methods.equals(clsAttrs.methods);
+        }
+
+        @Override
+        public int hashCode() {
+            int result = 17;
+            result = 37 * result + access;
+            result = 37 * result + superName != null ? superName.hashCode() : 0;
+            result = 37 * result + fields.hashCode();
+            result = 37 * result + methods.hashCode();
+            return result;
+        }
+    }
+}
--- a/jdk/src/jdk.jartool/share/classes/sun/tools/jar/GNUStyleOptions.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/src/jdk.jartool/share/classes/sun/tools/jar/GNUStyleOptions.java	Wed Jul 05 22:05:22 2017 +0200
@@ -91,7 +91,7 @@
                     tool.xflag = true;
                 }
             },
-            new Option(false, OptionType.MAIN_OPERATION, "--print-module-descriptor", "-p") {
+            new Option(false, OptionType.MAIN_OPERATION, "--print-module-descriptor", "-d") {
                 void process(Main tool, String opt, String arg) throws BadArgs {
                     if (tool.cflag || tool.iflag  || tool.tflag || tool.uflag || tool.xflag)
                         throw new BadArgs("error.multiple.main.operations").showUsage(true);
@@ -145,7 +145,7 @@
                     }
                 }
             },
-            new Option(true, OptionType.CREATE_UPDATE, "--modulepath", "--mp") {
+            new Option(true, OptionType.CREATE_UPDATE, "--module-path", "-p") {
                 void process(Main jartool, String opt, String arg) {
                     String[] dirs = arg.split(File.pathSeparator);
                     Path[] paths = new Path[dirs.length];
--- a/jdk/src/jdk.jartool/share/classes/sun/tools/jar/Main.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/src/jdk.jartool/share/classes/sun/tools/jar/Main.java	Wed Jul 05 22:05:22 2017 +0200
@@ -42,6 +42,7 @@
 import java.nio.file.Path;
 import java.nio.file.Files;
 import java.nio.file.Paths;
+import java.nio.file.StandardCopyOption;
 import java.util.*;
 import java.util.function.Consumer;
 import java.util.function.Function;
@@ -278,23 +279,20 @@
                     }
                 }
             }
+
             if (cflag) {
                 Manifest manifest = null;
-                InputStream in = null;
-
                 if (!Mflag) {
                     if (mname != null) {
-                        in = new FileInputStream(mname);
-                        manifest = new Manifest(new BufferedInputStream(in));
+                        try (InputStream in = new FileInputStream(mname)) {
+                            manifest = new Manifest(new BufferedInputStream(in));
+                        }
                     } else {
                         manifest = new Manifest();
                     }
                     addVersion(manifest);
                     addCreatedBy(manifest);
                     if (isAmbiguousMainClass(manifest)) {
-                        if (in != null) {
-                            in.close();
-                        }
                         return false;
                     }
                     if (ename != null) {
@@ -304,11 +302,13 @@
                         addMultiRelease(manifest);
                     }
                 }
+
                 Map<String,Path> moduleInfoPaths = new HashMap<>();
                 for (int version : filesMap.keySet()) {
                     String[] files = filesMap.get(version);
                     expand(null, files, false, moduleInfoPaths, version);
                 }
+
                 Map<String,byte[]> moduleInfos = new LinkedHashMap<>();
                 if (!moduleInfoPaths.isEmpty()) {
                     if (!checkModuleInfos(moduleInfoPaths))
@@ -332,84 +332,61 @@
                     return false;
                 }
 
-                OutputStream out;
-                if (fname != null) {
-                    out = new FileOutputStream(fname);
-                } else {
-                    out = new FileOutputStream(FileDescriptor.out);
-                    if (vflag) {
-                        // Disable verbose output so that it does not appear
-                        // on stdout along with file data
-                        // error("Warning: -v option ignored");
-                        vflag = false;
-                    }
+                if (vflag && fname == null) {
+                    // Disable verbose output so that it does not appear
+                    // on stdout along with file data
+                    // error("Warning: -v option ignored");
+                    vflag = false;
                 }
-                File tmpfile = null;
-                final OutputStream finalout = out;
+
                 final String tmpbase = (fname == null)
                         ? "tmpjar"
                         : fname.substring(fname.indexOf(File.separatorChar) + 1);
-                if (nflag) {
-                    tmpfile = createTemporaryFile(tmpbase, ".jar");
-                    out = new FileOutputStream(tmpfile);
-                }
-                create(new BufferedOutputStream(out, 4096), manifest, moduleInfos);
+                File tmpfile = createTemporaryFile(tmpbase, ".jar");
 
-                if (in != null) {
-                    in.close();
+                try (OutputStream out = new FileOutputStream(tmpfile)) {
+                    create(new BufferedOutputStream(out, 4096), manifest, moduleInfos);
                 }
-                out.close();
+
                 if (nflag) {
-                    JarFile jarFile = null;
-                    File packFile = null;
-                    JarOutputStream jos = null;
+                    File packFile = createTemporaryFile(tmpbase, ".pack");
                     try {
                         Packer packer = Pack200.newPacker();
                         Map<String, String> p = packer.properties();
                         p.put(Packer.EFFORT, "1"); // Minimal effort to conserve CPU
-                        jarFile = new JarFile(tmpfile.getCanonicalPath());
-                        packFile = createTemporaryFile(tmpbase, ".pack");
-                        out = new FileOutputStream(packFile);
-                        packer.pack(jarFile, out);
-                        jos = new JarOutputStream(finalout);
-                        Unpacker unpacker = Pack200.newUnpacker();
-                        unpacker.unpack(packFile, jos);
-                    } catch (IOException ioe) {
-                        fatalError(ioe);
-                    } finally {
-                        if (jarFile != null) {
-                            jarFile.close();
+                        try (
+                                JarFile jarFile = new JarFile(tmpfile.getCanonicalPath());
+                                OutputStream pack = new FileOutputStream(packFile)
+                        ) {
+                            packer.pack(jarFile, pack);
                         }
-                        if (out != null) {
-                            out.close();
-                        }
-                        if (jos != null) {
-                            jos.close();
-                        }
-                        if (tmpfile != null && tmpfile.exists()) {
+                        if (tmpfile.exists()) {
                             tmpfile.delete();
                         }
-                        if (packFile != null && packFile.exists()) {
-                            packFile.delete();
+                        tmpfile = createTemporaryFile(tmpbase, ".jar");
+                        try (
+                                OutputStream out = new FileOutputStream(tmpfile);
+                                JarOutputStream jos = new JarOutputStream(out)
+                        ) {
+                            Unpacker unpacker = Pack200.newUnpacker();
+                            unpacker.unpack(packFile, jos);
                         }
+                    } finally {
+                        Files.deleteIfExists(packFile.toPath());
                     }
                 }
+
+                validateAndClose(tmpfile);
+
             } else if (uflag) {
                 File inputFile = null, tmpFile = null;
-                FileInputStream in;
-                FileOutputStream out;
                 if (fname != null) {
                     inputFile = new File(fname);
                     tmpFile = createTempFileInSameDirectoryAs(inputFile);
-                    in = new FileInputStream(inputFile);
-                    out = new FileOutputStream(tmpFile);
                 } else {
-                    in = new FileInputStream(FileDescriptor.in);
-                    out = new FileOutputStream(FileDescriptor.out);
                     vflag = false;
+                    tmpFile = createTemporaryFile("tmpjar", ".jar");
                 }
-                InputStream manifest = (!Mflag && (mname != null)) ?
-                    (new FileInputStream(mname)) : null;
 
                 Map<String,Path> moduleInfoPaths = new HashMap<>();
                 for (int version : filesMap.keySet()) {
@@ -421,8 +398,19 @@
                 for (Map.Entry<String,Path> e : moduleInfoPaths.entrySet())
                     moduleInfos.put(e.getKey(), readModuleInfo(e.getValue()));
 
-                boolean updateOk = update(in, new BufferedOutputStream(out),
-                                          manifest, moduleInfos, null);
+                try (
+                        FileInputStream in = (fname != null) ? new FileInputStream(inputFile)
+                                : new FileInputStream(FileDescriptor.in);
+                        FileOutputStream out = new FileOutputStream(tmpFile);
+                        InputStream manifest = (!Mflag && (mname != null)) ?
+                                (new FileInputStream(mname)) : null;
+                ) {
+                        boolean updateOk = update(in, new BufferedOutputStream(out),
+                                manifest, moduleInfos, null);
+                        if (ok) {
+                            ok = updateOk;
+                        }
+                }
 
                 // Consistency checks for modular jars.
                 if (!moduleInfos.isEmpty()) {
@@ -430,23 +418,8 @@
                         return false;
                 }
 
-                if (ok) {
-                    ok = updateOk;
-                }
-                in.close();
-                out.close();
-                if (manifest != null) {
-                    manifest.close();
-                }
-                if (ok && fname != null) {
-                    // on Win32, we need this delete
-                    inputFile.delete();
-                    if (!tmpFile.renameTo(inputFile)) {
-                        tmpFile.delete();
-                        throw new IOException(getMsg("error.write.file"));
-                    }
-                    tmpFile.delete();
-                }
+                validateAndClose(tmpFile);
+
             } else if (tflag) {
                 replaceFSC(filesMap);
                 // For the "list table contents" action, access using the
@@ -520,6 +493,28 @@
         return ok;
     }
 
+    private void validateAndClose(File tmpfile) throws IOException {
+        if (ok && isMultiRelease) {
+            ok = validate(tmpfile.getCanonicalPath());
+            if (!ok) {
+                error(formatMsg("error.validator.jarfile.invalid", fname));
+            }
+        }
+
+        Path path = tmpfile.toPath();
+        try {
+            if (ok) {
+                if (fname != null) {
+                    Files.move(path, Paths.get(fname), StandardCopyOption.REPLACE_EXISTING);
+                } else {
+                    Files.copy(path, new FileOutputStream(FileDescriptor.out));
+                }
+            }
+        } finally {
+            Files.deleteIfExists(path);
+        }
+    }
+
     private String[] filesMapToFiles(Map<Integer,String[]> filesMap) {
         if (filesMap.isEmpty()) return null;
         return filesMap.entrySet()
@@ -534,6 +529,76 @@
                 .map(f -> (new EntryName(f, version)).entryName);
     }
 
+    // sort base entries before versioned entries, and sort entry classes with
+    // nested classes so that the top level class appears before the associated
+    // nested class
+    private Comparator<JarEntry> entryComparator = (je1, je2) ->  {
+        String s1 = je1.getName();
+        String s2 = je2.getName();
+        if (s1.equals(s2)) return 0;
+        boolean b1 = s1.startsWith(VERSIONS_DIR);
+        boolean b2 = s2.startsWith(VERSIONS_DIR);
+        if (b1 && !b2) return 1;
+        if (!b1 && b2) return -1;
+        int n = 0; // starting char for String compare
+        if (b1 && b2) {
+            // normally strings would be sorted so "10" goes before "9", but
+            // version number strings need to be sorted numerically
+            n = VERSIONS_DIR.length();   // skip the common prefix
+            int i1 = s1.indexOf('/', n);
+            int i2 = s1.indexOf('/', n);
+            if (i1 == -1) throw new InvalidJarException(s1);
+            if (i2 == -1) throw new InvalidJarException(s2);
+            // shorter version numbers go first
+            if (i1 != i2) return i1 - i2;
+            // otherwise, handle equal length numbers below
+        }
+        int l1 = s1.length();
+        int l2 = s2.length();
+        int lim = Math.min(l1, l2);
+        for (int k = n; k < lim; k++) {
+            char c1 = s1.charAt(k);
+            char c2 = s2.charAt(k);
+            if (c1 != c2) {
+                // change natural ordering so '.' comes before '$'
+                // i.e. top level classes come before nested classes
+                if (c1 == '$' && c2 == '.') return 1;
+                if (c1 == '.' && c2 == '$') return -1;
+                return c1 - c2;
+            }
+        }
+        return l1 - l2;
+    };
+
+    private boolean validate(String fname) {
+        boolean valid;
+
+        try (JarFile jf = new JarFile(fname)) {
+            Validator validator = new Validator(this, jf);
+            jf.stream()
+                    .filter(e -> !e.isDirectory())
+                    .filter(e -> !e.getName().equals(MANIFEST_NAME))
+                    .filter(e -> !e.getName().endsWith(MODULE_INFO))
+                    .sorted(entryComparator)
+                    .forEachOrdered(validator);
+             valid = validator.isValid();
+        } catch (IOException e) {
+            error(formatMsg2("error.validator.jarfile.exception", fname, e.getMessage()));
+            valid = false;
+        } catch (InvalidJarException e) {
+            error(formatMsg("error.validator.bad.entry.name", e.getMessage()));
+            valid = false;
+        }
+        return valid;
+    }
+
+    private static class InvalidJarException extends RuntimeException {
+        private static final long serialVersionUID = -3642329147299217726L;
+        InvalidJarException(String msg) {
+            super(msg);
+        }
+    }
+
     /**
      * Parses command line arguments.
      */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/jdk.jartool/share/classes/sun/tools/jar/Validator.java	Wed Jul 05 22:05:22 2017 +0200
@@ -0,0 +1,242 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package sun.tools.jar;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.function.Consumer;
+import java.util.jar.JarEntry;
+import java.util.jar.JarFile;
+
+final class Validator implements Consumer<JarEntry> {
+    private final static boolean DEBUG = Boolean.getBoolean("jar.debug");
+    private final  Map<String,FingerPrint> fps = new HashMap<>();
+    private final int vdlen = Main.VERSIONS_DIR.length();
+    private final Main main;
+    private final JarFile jf;
+    private int oldVersion = -1;
+    private String currentTopLevelName;
+    private boolean isValid = true;
+
+    Validator(Main main, JarFile jf) {
+        this.main = main;
+        this.jf = jf;
+    }
+
+    boolean isValid() {
+        return isValid;
+    }
+
+    /*
+     *  Validator has state and assumes entries provided to accept are ordered
+     *  from base entries first and then through the versioned entries in
+     *  ascending version order.  Also, to find isolated nested classes,
+     *  classes must be ordered so that the top level class is before the associated
+     *  nested class(es).
+    */
+    public void accept(JarEntry je) {
+        String entryName = je.getName();
+
+        // directories are always accepted
+        if (entryName.endsWith("/")) {
+            debug("%s is a directory", entryName);
+            return;
+        }
+
+        // figure out the version and basename from the JarEntry
+        int version;
+        String basename;
+        if (entryName.startsWith(Main.VERSIONS_DIR)) {
+            int n = entryName.indexOf("/", vdlen);
+            if (n == -1) {
+                main.error(Main.formatMsg("error.validator.version.notnumber", entryName));
+                isValid = false;
+                return;
+            }
+            String v = entryName.substring(vdlen, n);
+            try {
+                version = Integer.parseInt(v);
+            } catch (NumberFormatException x) {
+                main.error(Main.formatMsg("error.validator.version.notnumber", entryName));
+                isValid = false;
+                return;
+            }
+            if (n == entryName.length()) {
+                main.error(Main.formatMsg("error.validator.entryname.tooshort", entryName));
+                isValid = false;
+                return;
+            }
+            basename = entryName.substring(n + 1);
+        } else {
+            version = 0;
+            basename = entryName;
+        }
+        debug("\n===================\nversion %d %s", version, entryName);
+
+        if (oldVersion != version) {
+            oldVersion = version;
+            currentTopLevelName = null;
+        }
+
+        // analyze the entry, keeping key attributes
+        FingerPrint fp;
+        try (InputStream is = jf.getInputStream(je)) {
+            fp = new FingerPrint(basename, is.readAllBytes());
+        } catch (IOException x) {
+            main.error(x.getMessage());
+            isValid = false;
+            return;
+        }
+        String internalName = fp.name();
+
+        // process a base entry paying attention to nested classes
+        if (version == 0) {
+            debug("base entry found");
+            if (fp.isNestedClass()) {
+                debug("nested class found");
+                if (fp.topLevelName().equals(currentTopLevelName)) {
+                    fps.put(internalName, fp);
+                    return;
+                }
+                main.error(Main.formatMsg("error.validator.isolated.nested.class", entryName));
+                isValid = false;
+                return;
+            }
+            // top level class or resource entry
+            if (fp.isClass()) {
+                currentTopLevelName = fp.topLevelName();
+                if (!checkInternalName(entryName, basename, internalName)) {
+                    isValid = false;
+                    return;
+                }
+            }
+            fps.put(internalName, fp);
+            return;
+        }
+
+        // process a versioned entry, look for previous entry with same name
+        FingerPrint matchFp = fps.get(internalName);
+        debug("looking for match");
+        if (matchFp == null) {
+            debug("no match found");
+            if (fp.isClass()) {
+                if (fp.isNestedClass()) {
+                    if (!checkNestedClass(version, entryName, internalName, fp)) {
+                        isValid = false;
+                    }
+                    return;
+                }
+                if (fp.isPublicClass()) {
+                    main.error(Main.formatMsg("error.validator.new.public.class", entryName));
+                    isValid = false;
+                    return;
+                }
+                debug("%s is a non-public class entry", entryName);
+                fps.put(internalName, fp);
+                currentTopLevelName = fp.topLevelName();
+                return;
+            }
+            debug("%s is a resource entry");
+            fps.put(internalName, fp);
+            return;
+        }
+        debug("match found");
+
+        // are the two classes/resources identical?
+        if (fp.isIdentical(matchFp)) {
+            main.error(Main.formatMsg("error.validator.identical.entry", entryName));
+            return;  // it's okay, just takes up room
+        }
+        debug("sha1 not equal -- different bytes");
+
+        // ok, not identical, check for compatible class version and api
+        if (fp.isClass()) {
+            if (fp.isNestedClass()) {
+                if (!checkNestedClass(version, entryName, internalName, fp)) {
+                    isValid = false;
+                }
+                return;
+            }
+            debug("%s is a class entry", entryName);
+            if (!fp.isCompatibleVersion(matchFp)) {
+                main.error(Main.formatMsg("error.validator.incompatible.class.version", entryName));
+                isValid = false;
+                return;
+            }
+            if (!fp.isSameAPI(matchFp)) {
+                main.error(Main.formatMsg("error.validator.different.api", entryName));
+                isValid = false;
+                return;
+            }
+            if (!checkInternalName(entryName, basename, internalName)) {
+                isValid = false;
+                return;
+            }
+            debug("fingerprints same -- same api");
+            fps.put(internalName, fp);
+            currentTopLevelName = fp.topLevelName();
+            return;
+        }
+        debug("%s is a resource", entryName);
+
+        main.error(Main.formatMsg("error.validator.resources.with.same.name", entryName));
+        fps.put(internalName, fp);
+        return;
+    }
+
+    private boolean checkInternalName(String entryName, String basename, String internalName) {
+        String className = className(basename);
+        if (internalName.equals(className)) {
+            return true;
+        }
+        main.error(Main.formatMsg2("error.validator.names.mismatch",
+                entryName, internalName.replace("/", ".")));
+        return false;
+    }
+
+    private boolean checkNestedClass(int version, String entryName, String internalName, FingerPrint fp) {
+        debug("%s is a nested class entry in top level class %s", entryName, fp.topLevelName());
+        if (fp.topLevelName().equals(currentTopLevelName)) {
+            debug("%s (top level class) was accepted", fp.topLevelName());
+            fps.put(internalName, fp);
+            return true;
+        }
+        debug("top level class was not accepted");
+        main.error(Main.formatMsg("error.validator.isolated.nested.class", entryName));
+        return false;
+    }
+
+    private String className(String entryName) {
+        return entryName.endsWith(".class") ? entryName.substring(0, entryName.length() - 6) : null;
+    }
+
+    private void debug(String fmt, Object... args) {
+        if (DEBUG) System.err.format(fmt, args);
+    }
+}
+
--- a/jdk/src/jdk.jartool/share/classes/sun/tools/jar/resources/jar.properties	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/src/jdk.jartool/share/classes/sun/tools/jar/resources/jar.properties	Wed Jul 05 22:05:22 2017 +0200
@@ -85,6 +85,30 @@
         release {0} not valid
 error.release.value.toosmall=\
         release {0} not valid, must be >= 9
+error.validator.jarfile.exception=\
+        can not validate {0}: {1}
+error.validator.jarfile.invalid=\
+        invalid multi-release jar file {0} deleted
+error.validator.bad.entry.name=\
+        entry name malformed, {0}
+error.validator.version.notnumber=\
+        entry name: {0}, does not have a version number
+error.validator.entryname.tooshort=\
+        entry name: {0}, too short, not a directory
+error.validator.isolated.nested.class=\
+        entry: {0}, is an isolated nested class
+error.validator.new.public.class=\
+        entry: {0}, contains a new public class not found in base entries
+error.validator.identical.entry=\
+        warning - entry: {0} contains a class that is identical to an entry already in the jar
+error.validator.incompatible.class.version=\
+        entry: {0}, has a class version incompatible with an earlier version
+error.validator.different.api=\
+        entry: {0}, contains a class with different api from earlier version
+error.validator.resources.with.same.name=\
+         warning - entry: {0}, multiple resources with same name
+error.validator.names.mismatch=\
+         entry: {0}, contains a class with internal name {1}, names do not match
 out.added.manifest=\
         added manifest
 out.added.module-info=\
@@ -177,7 +201,7 @@
 main.help.opt.main.extract=\
 \  -x, --extract              Extract named (or all) files from the archive
 main.help.opt.main.print-module-descriptor=\
-\  -p, --print-module-descriptor  Print the module descriptor
+\  -d, --print-module-descriptor  Print the module descriptor
 main.help.opt.any=\
 \ Operation modifiers valid in any mode:\n\
 \n\
@@ -208,8 +232,8 @@
 \                             matched by the given pattern and that depend upon\n\
 \                             directly or indirectly on a modular jar being\n\
 \                             created or a non-modular jar being updated
-main.help.opt.create.update.modulepath=\
-\      --modulepath           Location of module dependence for generating
+main.help.opt.create.update.module-path=\
+\  -p, --module-path          Location of module dependence for generating\n\
 \                             the hash
 main.help.opt.create.update.index=\
 \ Operation modifiers valid only in create, update, and generate-index mode:\n
@@ -226,7 +250,7 @@
 \ located in the root of the given directories, or the root of the jar archive\n\
 \ itself. The following operations are only valid when creating a modular jar,\n\
 \ or updating an existing non-modular jar: '--module-version',\n\
-\ '--hash-modules', and '--modulepath'.\n\
+\ '--hash-modules', and '--module-path'.\n\
 \n\
 \ Mandatory or optional arguments to long options are also mandatory or optional\n\
-\ for any corresponding short options.
\ No newline at end of file
+\ for any corresponding short options.
--- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jimage/JImageTask.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jimage/JImageTask.java	Wed Jul 05 22:05:22 2017 +0200
@@ -61,11 +61,11 @@
 
         new Option<JImageTask>(false, (task, option, arg) -> {
             task.options.fullVersion = true;
-        }, true, "--fullversion"),
+        }, true, "--full-version"),
 
         new Option<JImageTask>(false, (task, option, arg) -> {
             task.options.help = true;
-        }, "--help"),
+        }, "--help", "-h"),
 
         new Option<JImageTask>(false, (task, option, arg) -> {
             task.options.verbose = true;
--- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jimage/resources/jimage.properties	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jimage/resources/jimage.properties	Wed Jul 05 22:05:22 2017 +0200
@@ -25,7 +25,7 @@
 
 main.usage.summary=\
 Usage: {0} <extract | info | list | verify> <options> jimage...\n\
-use --help for a list of possible options.
+use -h or --help for a list of possible options.
 
 main.usage=\
 Usage: {0} <extract | info | list | verify> <options> jimage...\n\
@@ -76,11 +76,11 @@
 \ used, one pattern per line\n\
 
 
-main.opt.fullversion=\
-\  --fullversion                     Print full version information
+main.opt.full-version=\
+\  --full-version                    Print full version information
 
 main.opt.help=\
-\  --help                            Print usage message
+\  -h,  --help                       Print usage message
 
 main.opt.verbose=\
 \  --verbose                         Listing prints entry size and offset attributes
--- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/JlinkTask.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/JlinkTask.java	Wed Jul 05 22:05:22 2017 +0200
@@ -84,31 +84,32 @@
     private static final Option<?>[] recognizedOptions = {
         new Option<JlinkTask>(false, (task, opt, arg) -> {
             task.options.help = true;
-        }, "--help"),
+        }, "--help", "-h"),
         new Option<JlinkTask>(true, (task, opt, arg) -> {
             String[] dirs = arg.split(File.pathSeparator);
+            int i = 0;
             Arrays.stream(dirs)
                   .map(Paths::get)
                   .forEach(task.options.modulePath::add);
-        }, "--modulepath", "--mp"),
+        }, "--module-path", "-p"),
         new Option<JlinkTask>(true, (task, opt, arg) -> {
             for (String mn : arg.split(",")) {
                 if (mn.isEmpty()) {
                     throw taskHelper.newBadArgs("err.mods.must.be.specified",
-                            "--limitmods");
+                            "--limit-modules");
                 }
                 task.options.limitMods.add(mn);
             }
-        }, "--limitmods"),
+        }, "--limit-modules"),
         new Option<JlinkTask>(true, (task, opt, arg) -> {
             for (String mn : arg.split(",")) {
                 if (mn.isEmpty()) {
                     throw taskHelper.newBadArgs("err.mods.must.be.specified",
-                            "--addmods");
+                            "--add-modules");
                 }
                 task.options.addMods.add(mn);
             }
-        }, "--addmods"),
+        }, "--add-modules"),
         new Option<JlinkTask>(true, (task, opt, arg) -> {
             Path path = Paths.get(arg);
             task.options.output = path;
@@ -134,10 +135,10 @@
         }, true, "--keep-packaged-modules"),
         new Option<JlinkTask>(true, (task, opt, arg) -> {
             task.options.saveoptsfile = arg;
-        }, "--saveopts"),
+        }, "--save-opts"),
         new Option<JlinkTask>(false, (task, opt, arg) -> {
             task.options.fullVersion = true;
-        }, true, "--fullversion"),};
+        }, true, "--full-version"),};
 
     private static final String PROGNAME = "jlink";
     private final OptionsValues options = new OptionsValues();
@@ -294,7 +295,7 @@
         try {
             options.addMods = checkAddMods(options.addMods);
         } catch (IllegalArgumentException ex) {
-            throw taskHelper.newBadArgs("err.mods.must.be.specified", "--addmods")
+            throw taskHelper.newBadArgs("err.mods.must.be.specified", "--add-modules")
                     .showUsage(true);
         }
         // First create the image provider
--- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/TaskHelper.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/TaskHelper.java	Wed Jul 05 22:05:22 2017 +0200
@@ -196,7 +196,7 @@
                         // This option is handled prior
                         // to have the options parsed.
                     },
-                    "--plugins-modulepath"));
+                    "--plugin-module-path"));
             mainOptions.add(new PlugOption(true, (task, opt, arg) -> {
                 Path path = Paths.get(arg);
                 if (!Files.exists(path) || !Files.isDirectory(path)) {
--- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/plugins/GenerateJLIClassesPlugin.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/plugins/GenerateJLIClassesPlugin.java	Wed Jul 05 22:05:22 2017 +0200
@@ -25,7 +25,6 @@
 package jdk.tools.jlink.internal.plugins;
 
 import java.lang.invoke.MethodType;
-import java.lang.reflect.Method;
 import java.util.Arrays;
 import java.util.EnumSet;
 import java.util.HashMap;
@@ -33,6 +32,8 @@
 import java.util.Map;
 import java.util.Set;
 import java.util.stream.Collectors;
+import jdk.internal.misc.SharedSecrets;
+import jdk.internal.misc.JavaLangInvokeAccess;
 import jdk.tools.jlink.plugin.ResourcePoolEntry;
 import jdk.tools.jlink.plugin.PluginException;
 import jdk.tools.jlink.plugin.ResourcePool;
@@ -54,9 +55,6 @@
 
     private static final String DESCRIPTION = PluginsResourceBundle.getDescription(NAME);
 
-    private static final String BMH = "java/lang/invoke/BoundMethodHandle";
-    private static final Method BMH_FACTORY_METHOD;
-
     private static final String DMH = "java/lang/invoke/DirectMethodHandle$Holder";
     private static final String DMH_INVOKE_VIRTUAL = "invokeVirtual";
     private static final String DMH_INVOKE_STATIC = "invokeStatic";
@@ -64,7 +62,9 @@
     private static final String DMH_NEW_INVOKE_SPECIAL = "newInvokeSpecial";
     private static final String DMH_INVOKE_INTERFACE = "invokeInterface";
     private static final String DMH_INVOKE_STATIC_INIT = "invokeStaticInit";
-    private static final Method DMH_FACTORY_METHOD;
+
+    private static final JavaLangInvokeAccess JLIA
+            = SharedSecrets.getJavaLangInvokeAccess();
 
     List<String> speciesTypes;
 
@@ -232,8 +232,8 @@
     private void generateBMHClass(String types, ResourcePoolBuilder out) {
         try {
             // Generate class
-            Map.Entry<String, byte[]> result = (Map.Entry<String, byte[]>)
-                    BMH_FACTORY_METHOD.invoke(null, types);
+            Map.Entry<String, byte[]> result =
+                    JLIA.generateConcreteBMHClassBytes(types);
             String className = result.getKey();
             byte[] bytes = result.getValue();
 
@@ -264,11 +264,8 @@
             }
         }
         try {
-            byte[] bytes = (byte[])DMH_FACTORY_METHOD
-                    .invoke(null,
-                            DMH,
-                            methodTypes,
-                            dmhTypes);
+            byte[] bytes =
+                    JLIA.generateDMHClassBytes(DMH, methodTypes, dmhTypes);
             ResourcePoolEntry ndata = ResourcePoolEntry.create(DMH_ENTRY, bytes);
             out.add(ndata);
         } catch (Exception ex) {
@@ -277,22 +274,6 @@
     }
     private static final String DMH_ENTRY = "/java.base/" + DMH + ".class";
 
-    static {
-        try {
-            Class<?> BMHFactory = Class.forName("java.lang.invoke.BoundMethodHandle$Factory");
-            BMH_FACTORY_METHOD = BMHFactory.getDeclaredMethod("generateConcreteBMHClassBytes",
-                    String.class);
-            BMH_FACTORY_METHOD.setAccessible(true);
-
-            Class<?> DMHFactory = Class.forName("java.lang.invoke.DirectMethodHandle");
-            DMH_FACTORY_METHOD = DMHFactory.getDeclaredMethod("generateDMHClassBytes",
-                    String.class, MethodType[].class, int[].class);
-            DMH_FACTORY_METHOD.setAccessible(true);
-        } catch (Exception e) {
-            throw new PluginException(e);
-        }
-    }
-
     // Convert LL -> LL, L3 -> LLL
     private static String expandSignature(String signature) {
         StringBuilder sb = new StringBuilder();
--- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/resources/jlink.properties	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/resources/jlink.properties	Wed Jul 05 22:05:22 2017 +0200
@@ -24,30 +24,31 @@
 #
 
 main.usage.summary=\
-Usage: {0} <options> --modulepath <modulepath> --addmods <mods> --output <path>\n\
+Usage: {0} <options> --module-path <modulepath> --add-modules <mods> --output <path>\n\
 use --help for a list of possible options
 
 main.usage=\
-Usage: {0} <options> --modulepath <modulepath> --addmods <mods> --output <path>\n\
+Usage: {0} <options> --module-path <modulepath> --add-modules <mods> --output <path>\n\
 \Possible options include:
 
 error.prefix=Error:
 warn.prefix=Warning:
 
 main.opt.help=\
-\  --help                            Print this help message
+\  -h, --help                        Print this help message
 
 main.opt.version=\
 \  --version                         Version information
 
-main.opt.modulepath=\
-\  --modulepath <modulepath>         Module path
+main.opt.module-path=\
+\  -p <modulepath>\n\
+\  --module-path <modulepath>        Module path
 
-main.opt.addmods=\
-\  --addmods <mod>[,<mod>...]        Root modules to resolve
+main.opt.add-modules=\
+\  --add-modules <mod>[,<mod>...]    Root modules to resolve
 
-main.opt.limitmods=\
-\  --limitmods <mod>[,<mod>...]      Limit the universe of observable modules
+main.opt.limit-modules=\
+\  --limit-modules <mod>[,<mod>...]  Limit the universe of observable modules
 
 main.opt.output=\
 \  --output <path>                   Location of output path
@@ -58,8 +59,8 @@
 main.opt.endian=\
 \  --endian <little|big>             Byte order of generated jimage (default:native)
 
-main.opt.saveopts=\
-\  --saveopts <filename>             Save jlink options in the given file
+main.opt.save-opts=\
+\  --save-opts <filename>            Save jlink options in the given file
 
 main.msg.bug=\
 An exception has occurred in jlink. \
@@ -83,7 +84,7 @@
 
 err.unknown.byte.order:unknown byte order {0}
 err.output.must.be.specified:--output must be specified
-err.modulepath.must.be.specified:--modulepath must be specified
+err.modulepath.must.be.specified:--module-path must be specified
 err.mods.must.be.specified:no modules specified to {0}
 err.path.not.found=path not found: {0}
 err.path.not.valid=invalid path: {0}
--- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/resources/plugins.properties	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/resources/plugins.properties	Wed Jul 05 22:05:22 2017 +0200
@@ -115,7 +115,7 @@
 Invalid language tag: %s
 
 include-locales.localedatanotfound=\
-jdk.localedata module was not specified with --addmods option
+jdk.localedata module was not specified with --add-modules option
 
 main.status.ok=Functional.
 
@@ -133,8 +133,8 @@
 plugin.opt.resources-last-sorter=\
 \  --resources-last-sorter <name>    The last plugin allowed to sort resources
 
-plugin.opt.plugins-modulepath=\
-\  --plugin-module-path <modulepath> Custom plugins module path
+plugin.opt.plugin-module-path=\
+\  --plugin-module-path <modulepath> Custom plugin module path
 
 plugin.opt.c=\
 \  -c, --compress=2                  Enable compression of resources (level 2)
--- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jmod/JmodTask.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jmod/JmodTask.java	Wed Jul 05 22:05:22 2017 +0200
@@ -1181,7 +1181,7 @@
         }
     }
 
-    private final OptionParser parser = new OptionParser();
+    private final OptionParser parser = new OptionParser("hp");
 
     private void handleOptions(String[] args) {
         parser.formatHelpWith(new JmodHelpFormatter());
@@ -1218,7 +1218,7 @@
                         .withValuesConvertedBy(new PatternConverter());
 
         OptionSpec<Void> help
-                = parser.accepts("help", getMessage("main.opt.help"))
+                = parser.acceptsAll(Set.of("h", "help"), getMessage("main.opt.help"))
                         .forHelp();
 
         OptionSpec<Path> libs
@@ -1232,9 +1232,9 @@
                         .withRequiredArg()
                         .describedAs(getMessage("main.opt.main-class.arg"));
 
-        OptionSpec<Path> modulePath  // TODO: short version of --mp ??
-                = parser.acceptsAll(Arrays.asList("mp", "modulepath"),
-                                    getMessage("main.opt.modulepath"))
+        OptionSpec<Path> modulePath
+                = parser.acceptsAll(Set.of("p", "module-path"),
+                                    getMessage("main.opt.module-path"))
                         .withRequiredArg()
                         .withValuesSeparatedBy(File.pathSeparatorChar)
                         .withValuesConvertedBy(DirPathConverter.INSTANCE);
--- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jmod/resources/jmod.properties	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jmod/resources/jmod.properties	Wed Jul 05 22:05:22 2017 +0200
@@ -63,7 +63,7 @@
 main.opt.os-arch.arg=os-arch
 main.opt.os-version=Operating system version
 main.opt.os-version.arg=os-version
-main.opt.modulepath=Module path
+main.opt.module-path=Module path
 main.opt.hash-modules=Compute and record hashes to tie a packaged module\
 \ with modules matching the given <regex-pattern> and depending upon it directly\
 \ or indirectly. The hashes are recorded in the JMOD file being created, or\
--- a/jdk/test/ProblemList.txt	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/ProblemList.txt	Wed Jul 05 22:05:22 2017 +0200
@@ -133,15 +133,13 @@
 
 # jdk_instrument
 
-java/lang/instrument/RedefineBigClass.sh                        8061177 generic-all
-java/lang/instrument/RetransformBigClass.sh                     8061177 generic-all
+java/lang/instrument/RedefineBigClass.sh                        8065756 generic-all
+java/lang/instrument/RetransformBigClass.sh                     8065756 generic-all
 
 java/lang/instrument/BootClassPath/BootClassPathTest.sh         8072130 macosx-all
 
 java/lang/instrument/DaemonThread/TestDaemonThread.java         8161225 generic-all
 
-java/lang/management/MemoryMXBean/LowMemoryTest.java            8130339 generic-all
-
 java/lang/management/MemoryMXBean/Pending.java                  8158837 generic-all
 java/lang/management/MemoryMXBean/PendingAllGC.sh               8158760 generic-all
 
@@ -235,8 +233,8 @@
 sun/security/pkcs11/KeyAgreement/TestDH.java                    8077138,8023434 windows-all
 sun/security/pkcs11/KeyAgreement/TestInterop.java               8077138,8023434 windows-all
 sun/security/pkcs11/KeyAgreement/TestShort.java                 8077138,8023434 windows-all
-sun/security/pkcs11/KeyAgreement/SupportedDHKeys.java           8154910 windows-all
-sun/security/pkcs11/KeyAgreement/UnsupportedDHKeys.java         8154910 windows-all
+sun/security/pkcs11/KeyAgreement/SupportedDHKeys.java           8077138 windows-all
+sun/security/pkcs11/KeyAgreement/UnsupportedDHKeys.java         8077138 windows-all
 sun/security/pkcs11/KeyGenerator/DESParity.java                 8077138,8023434 windows-all
 sun/security/pkcs11/KeyGenerator/TestKeyGenerator.java          8077138,8023434 windows-all
 sun/security/pkcs11/KeyPairGenerator/TestDH2048.java            8077138,8023434 windows-all
@@ -287,7 +285,6 @@
 
 sun/security/krb5/auto/HttpNegotiateServer.java                 8038079 generic-all
 
-sun/security/tools/keytool/autotest.sh                          8130302 generic-all
 sun/security/ssl/SSLSocketImpl/AsyncSSLSocketClose.java         8161232 macosx-all
 
 ############################################################################
@@ -331,18 +328,17 @@
 
 com/sun/jdi/RedefineImplementor.sh                              8004127 generic-all
 
-com/sun/jdi/JdbMethodExitTest.sh                                8031555 generic-all
+com/sun/jdi/JdbMethodExitTest.sh                                6902121 generic-all
 
 com/sun/jdi/RepStep.java                                        8043571 generic-all
 
-com/sun/jdi/RedefinePop.sh                                      8058616 generic-all
-
-com/sun/jdi/CatchPatternTest.sh                                 8068645 generic-all
-
 com/sun/jdi/GetLocalVariables4Test.sh                           8067354 windows-all
 
 com/sun/jdi/sde/SourceDebugExtensionTest.java                   8158066 windows-all
 
+com/sun/jdi/ClassesByName2Test.java				8160833 generic-all
+com/sun/jdi/RedefineCrossEvent.java				8160833 generic-all
+
 ############################################################################
 
 # jdk_time
@@ -371,8 +367,6 @@
 
 sun/tools/jhsdb/heapconfig/JMapHeapConfigTest.java              8160376 macosx-all
 
-sun/tools/jstatd/TestJstatdExternalRegistry.java                8046285 generic-all
-
 sun/tools/jps/TestJpsJar.java                                   8160923 generic-all
 
 sun/tools/jps/TestJpsJarRelative.java                           6456333 generic-all
--- a/jdk/test/TEST.ROOT	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/TEST.ROOT	Wed Jul 05 22:05:22 2017 +0200
@@ -26,12 +26,12 @@
 # Allow querying of various System properties in @requires clauses
 requires.properties=sun.arch.data.model java.runtime.name
 
-# Tests using jtreg 4.2 b02 features
-requiredVersion=4.2 b02
+# Tests using jtreg 4.2 b03 features
+requiredVersion=4.2 b03
 
 # Path to libraries in the topmost test directory. This is needed so @library
 # does not need ../../ notation to reach them
 external.lib.roots = ../../
 
-# Use new form of -Xpatch
-useNewXpatch=true
+# Use new module options
+useNewOptions=true
--- a/jdk/test/com/sun/corba/5036554/TestCorbaBug.sh	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/com/sun/corba/5036554/TestCorbaBug.sh	Wed Jul 05 22:05:22 2017 +0200
@@ -81,9 +81,9 @@
 
 chmod -fR 777 bug
 
-${COMPILEJAVA}${FS}bin${FS}javac -addmods java.corba -d . bug${FS}*.java
+${COMPILEJAVA}${FS}bin${FS}javac --add-modules java.corba -d . bug${FS}*.java
 
-${TESTJAVA}${FS}bin${FS}java ${TESTVMOPTS} -addmods java.corba -cp . bug/JavaBug > test.out 2>&1 
+${TESTJAVA}${FS}bin${FS}java ${TESTVMOPTS} --add-modules java.corba -cp . bug/JavaBug > test.out 2>&1 
 
 grep "NullPointerException" test.out
 
--- a/jdk/test/com/sun/corba/7130985/CorbaExceptionsCompileTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/com/sun/corba/7130985/CorbaExceptionsCompileTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -27,8 +27,8 @@
  * @summary Four helper classes missing in Sun JDK
  * @library /lib/testlibrary
  * @build jdk.testlibrary.*
- * @compile -addmods java.corba CorbaExceptionsCompileTest.java
- * @run main/othervm -addmods java.corba CorbaExceptionsCompileTest
+ * @modules java.corba
+ * @run main CorbaExceptionsCompileTest
  */
 
 import java.io.*;
--- a/jdk/test/com/sun/corba/se/impl/io/HookPutFieldsTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/com/sun/corba/se/impl/io/HookPutFieldsTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -25,8 +25,8 @@
  * @test
  * @bug 7095856
  * @summary OutputStreamHook doesn't handle null values
- * @compile -addmods java.corba HookPutFieldsTest.java
- * @run main/othervm -addmods java.corba HookPutFieldsTest
+ * @modules java.corba
+ * @run main HookPutFieldsTest
  */
 
 import java.net.InetAddress;
--- a/jdk/test/com/sun/corba/se/impl/orb/SetDefaultORBTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/com/sun/corba/se/impl/orb/SetDefaultORBTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -25,8 +25,8 @@
  * @test
  * @bug 8028215
  * @summary SetDefaultORBTest setting ORB impl via properties test
- * @compile -addmods java.corba SetDefaultORBTest.java
- * @run main/othervm -addmods java.corba SetDefaultORBTest
+ * @modules java.corba
+ * @run main SetDefaultORBTest
  *
  */
 
--- a/jdk/test/com/sun/jdi/ImmutableResourceTest.sh	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/com/sun/jdi/ImmutableResourceTest.sh	Wed Jul 05 22:05:22 2017 +0200
@@ -99,11 +99,11 @@
 set -vx
 #
 # Compile test class
-${TESTJAVA}/bin/javac -XaddExports:jdk.jdi/com.sun.tools.example.debug.tty=ALL-UNNAMED \
+${TESTJAVA}/bin/javac --add-exports jdk.jdi/com.sun.tools.example.debug.tty=ALL-UNNAMED \
    -d "${TESTCLASSES}" ${CP} -g "${TESTSRC}"/"${TARGETCLASS}".java
 #
 # Run the test class, again with the classpath we need:
-${TESTJAVA}/bin/java -XaddExports:jdk.jdi/com.sun.tools.example.debug.tty=ALL-UNNAMED \
+${TESTJAVA}/bin/java --add-exports jdk.jdi/com.sun.tools.example.debug.tty=ALL-UNNAMED \
     ${CP} ${TARGETCLASS}
 status=$?
 echo "test status was: $status"
--- a/jdk/test/com/sun/jndi/cosnaming/CNNameParser.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/com/sun/jndi/cosnaming/CNNameParser.java	Wed Jul 05 22:05:22 2017 +0200
@@ -26,6 +26,7 @@
  * @summary Tests that JNDI/COS naming parser supports the syntax
  * defined in the new INS standard.
  * @modules java.corba/com.sun.jndi.cosnaming
+ * @run main/othervm CNNameParser
  */
 
 import javax.naming.*;
--- a/jdk/test/com/sun/jndi/cosnaming/IiopUrlIPv6.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/com/sun/jndi/cosnaming/IiopUrlIPv6.java	Wed Jul 05 22:05:22 2017 +0200
@@ -25,6 +25,7 @@
  * @bug 5042453
  * @summary Ipv6 address throws Non-numeric port number error
  * @modules java.corba/com.sun.jndi.cosnaming
+ * @run main/othervm IiopUrlIPv6
  */
 
 import com.sun.jndi.cosnaming.*;
--- a/jdk/test/com/sun/management/HotSpotDiagnosticMXBean/CheckOrigin.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/com/sun/management/HotSpotDiagnosticMXBean/CheckOrigin.java	Wed Jul 05 22:05:22 2017 +0200
@@ -61,7 +61,7 @@
 
             ProcessBuilder pb = ProcessTools.
                 createJavaProcessBuilder(
-                    "-XaddExports:jdk.attach/sun.tools.attach=ALL-UNNAMED",
+                    "--add-exports", "jdk.attach/sun.tools.attach=ALL-UNNAMED",
                     "-XX:+UseConcMarkSweepGC",  // this will cause UseParNewGC to be FLAG_SET_ERGO
                     "-XX:+UseCodeAging",
                     "-XX:+UseCerealGC",         // Should be ignored.
--- a/jdk/test/java/awt/Gtk/GtkVersionTest/GtkVersionTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/awt/Gtk/GtkVersionTest/GtkVersionTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -55,7 +55,7 @@
                 "/bin/java " +
                 (version == null ? "" : "-Djdk.gtk.version=" + version) +
                 " -Djdk.gtk.verbose=true " +
-                "-XaddExports:java.desktop/sun.awt=ALL-UNNAMED " +
+                "--add-exports=java.desktop/sun.awt=ALL-UNNAMED " +
                 "-cp " + System.getProperty("java.class.path", ".") +
                 " GtkVersionTest$LoadGtk");
         p.waitFor();
--- a/jdk/test/java/awt/Toolkit/Headless/WrappedToolkitTest/WrappedToolkitTest.sh	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/awt/Toolkit/Headless/WrappedToolkitTest/WrappedToolkitTest.sh	Wed Jul 05 22:05:22 2017 +0200
@@ -113,8 +113,8 @@
 case "$OS" in
   Windows* | CYGWIN* )
     ${COMPILEJAVA}/bin/javac ${TESTJAVACOPTS} \
-                         -XaddExports:java.desktop/sun.awt=ALL-UNNAMED \
-                         -XaddExports:java.desktop/sun.awt.windows=ALL-UNNAMED ${CP} \
+                         --add-exports java.desktop/sun.awt=ALL-UNNAMED \
+                         --add-exports java.desktop/sun.awt.windows=ALL-UNNAMED ${CP} \
                          *.java
     status=$?
     if [ ! $status -eq "0" ]; then
@@ -124,8 +124,8 @@
 
   SunOS | Linux )
     ${COMPILEJAVA}/bin/javac ${TESTJAVACOPTS} \
-                         -XaddExports:java.desktop/sun.awt=ALL-UNNAMED \
-                         -XaddExports:java.desktop/sun.awt.X11=ALL-UNNAMED ${CP} \
+                         --add-exports java.desktop/sun.awt=ALL-UNNAMED \
+                         --add-exports java.desktop/sun.awt.X11=ALL-UNNAMED ${CP} \
                          *.java
     status=$?
     if [ ! $status -eq "0" ]; then
@@ -135,8 +135,8 @@
 
   Darwin)
     ${COMPILEJAVA}/bin/javac ${TESTJAVACOPTS} \
-                         -XaddExports:java.desktop/sun.awt=ALL-UNNAMED \
-                         -XaddExports:java.desktop/sun.lwawt.macosx=ALL-UNNAMED ${CP} \
+                         --add-exports java.desktop/sun.awt=ALL-UNNAMED \
+                         --add-exports java.desktop/sun.lwawt.macosx=ALL-UNNAMED ${CP} \
                          *.java
     status=$?
     if [ ! $status -eq "0" ]; then
@@ -154,16 +154,16 @@
 case "$OS" in
   Windows* | CYGWIN* )
     ${TESTJAVA}/bin/java ${TESTVMOPTS} -Djava.awt.headless=true \
-                         -XaddExports:java.desktop/sun.awt=ALL-UNNAMED \
-                         -XaddExports:java.desktop/sun.awt.windows=ALL-UNNAMED ${CP} \
+                         --add-exports java.desktop/sun.awt=ALL-UNNAMED \
+                         --add-exports java.desktop/sun.awt.windows=ALL-UNNAMED ${CP} \
                          TestWrapped sun.awt.windows.WToolkit
     status=$?
     if [ ! $status -eq "0" ]; then
       fail "Test FAILED: toolkit wrapped into HeadlessToolkit is not an instance of sun.awt.windows.WToolkit";
     fi
     ${TESTJAVA}/bin/java ${TESTVMOPTS} -Djava.awt.headless=true \
-                         -XaddExports:java.desktop/sun.awt=ALL-UNNAMED \
-                         -XaddExports:java.desktop/sun.awt.windows=ALL-UNNAMED ${CP} \
+                         --add-exports java.desktop/sun.awt=ALL-UNNAMED \
+                         --add-exports java.desktop/sun.awt.windows=ALL-UNNAMED ${CP} \
                          -Dawt.toolkit=sun.awt.windows.WToolkit \
                          TestWrapped sun.awt.windows.WToolkit
     status=$?
@@ -174,8 +174,8 @@
 
   SunOS | Linux )
     ${TESTJAVA}/bin/java ${TESTVMOPTS} -Djava.awt.headless=true \
-                         -XaddExports:java.desktop/sun.awt=ALL-UNNAMED \
-                         -XaddExports:java.desktop/sun.awt.X11=ALL-UNNAMED ${CP} \
+                         --add-exports java.desktop/sun.awt=ALL-UNNAMED \
+                         --add-exports java.desktop/sun.awt.X11=ALL-UNNAMED ${CP} \
                          -Dawt.toolkit=sun.awt.X11.XToolkit \
                          TestWrapped sun.awt.X11.XToolkit
     status=$?
@@ -183,8 +183,8 @@
       fail "Test FAILED: toolkit wrapped into HeadlessToolkit is not an instance of sun.awt.xawt.XToolkit";
     fi
     AWT_TOOLKIT=XToolkit ${TESTJAVA}/bin/java ${TESTVMOPTS} \
-                         -XaddExports:java.desktop/sun.awt=ALL-UNNAMED \
-                         -XaddExports:java.desktop/sun.awt.X11=ALL-UNNAMED ${CP} \
+                         --add-exports java.desktop/sun.awt=ALL-UNNAMED \
+                         --add-exports java.desktop/sun.awt.X11=ALL-UNNAMED ${CP} \
                                               -Djava.awt.headless=true \
                                               TestWrapped sun.awt.X11.XToolkit
     status=$?
@@ -195,16 +195,16 @@
 
   Darwin)
     ${TESTJAVA}/bin/java ${TESTVMOPTS} -Djava.awt.headless=true \
-                         -XaddExports:java.desktop/sun.awt=ALL-UNNAMED \
-                         -XaddExports:java.desktop/sun.lwawt.macosx=ALL-UNNAMED ${CP} \
+                         --add-exports java.desktop/sun.awt=ALL-UNNAMED \
+                         --add-exports java.desktop/sun.lwawt.macosx=ALL-UNNAMED ${CP} \
                          TestWrapped sun.lwawt.macosx.LWCToolkit
     status=$?
     if [ ! $status -eq "0" ]; then
       fail "Test FAILED: toolkit wrapped into HeadlessToolkit is not an instance of sun.lwawt.macosx.LWCToolkit";
     fi
     ${TESTJAVA}/bin/java ${TESTVMOPTS} -Djava.awt.headless=true \
-                         -XaddExports:java.desktop/sun.awt=ALL-UNNAMED \
-                         -XaddExports:java.desktop/sun.lwawt.macosx=ALL-UNNAMED ${CP} \
+                         --add-exports java.desktop/sun.awt=ALL-UNNAMED \
+                         --add-exports java.desktop/sun.lwawt.macosx=ALL-UNNAMED ${CP} \
                          -Dawt.toolkit=sun.lwawt.macosx.LWCToolkit \
                          TestWrapped sun.lwawt.macosx.LWCToolkit
     status=$?
--- a/jdk/test/java/awt/xembed/server/RunTestXEmbed.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/awt/xembed/server/RunTestXEmbed.java	Wed Jul 05 22:05:22 2017 +0200
@@ -73,10 +73,11 @@
                     enva[ind++] = "AWT_TOOLKIT=sun.awt.X11.XToolkit";
                 }
             }
-            Process proc = Runtime.getRuntime().exec(java_home +
-                                                     "/bin/java -XaddExports:java.desktop/sun.awt.X11=ALL-UNNAMED -Dawt.toolkit=sun.awt.X11.XToolkit TesterClient "
-                                                     + test.getName() + " " + window + buf,
-                                                     enva);
+            Process proc = Runtime.getRuntime().
+                exec(java_home +
+                     "/bin/java --add-exports java.desktop/sun.awt.X11=ALL-UNNAMED -Dawt.toolkit=sun.awt.X11.XToolkit TesterClient "
+                     + test.getName() + " " + window + buf,
+                     enva);
             System.err.println("Test for " + test.getName() + " has started.");
             log.fine("Test for " + test.getName() + " has started.");
             new InputReader(proc.getInputStream());
--- a/jdk/test/java/awt/xembed/server/TestXEmbedServerJava.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/awt/xembed/server/TestXEmbedServerJava.java	Wed Jul 05 22:05:22 2017 +0200
@@ -84,11 +84,11 @@
             }
             if (hasModules) {
                 System.out.println(java_home +
-                               "/bin/java  -XaddExports:java.desktop/sun.awt.X11=ALL-UNNAMED "+
-                               "-XaddExports:java.desktop/sun.awt=ALL-UNNAMED  JavaClient " + window);
+                               "/bin/java --add-exports java.desktop/sun.awt.X11=ALL-UNNAMED "+
+                               "--add-exports java.desktop/sun.awt=ALL-UNNAMED  JavaClient " + window);
                 return Runtime.getRuntime().exec(java_home +
-                               "/bin/java  -XaddExports:java.desktop/sun.awt.X11=ALL-UNNAMED "+
-                               "-XaddExports:java.desktop/sun.awt=ALL-UNNAMED  JavaClient " + window);
+                               "/bin/java --add-exports java.desktop/sun.awt.X11=ALL-UNNAMED "+
+                               "--add-exports java.desktop/sun.awt=ALL-UNNAMED  JavaClient " + window);
             }else{
                 System.out.println(java_home + "/bin/java JavaClient " + window);
                 return Runtime.getRuntime().exec(java_home + "/bin/java JavaClient " + window);
--- a/jdk/test/java/beans/XMLDecoder/8028054/TestConstructorFinder.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/beans/XMLDecoder/8028054/TestConstructorFinder.java	Wed Jul 05 22:05:22 2017 +0200
@@ -39,7 +39,7 @@
  *          java.corba
  *          java.xml.bind
  * @compile -XDignore.symbol.file TestConstructorFinder.java
- * @run main/othervm -addmods java.activation -addmods java.transaction -addmods java.corba -addmods java.xml.bind TestConstructorFinder
+ * @run main/othervm --add-modules=java.activation,java.transaction,java.corba,java.xml.bind TestConstructorFinder
  */
 
 public class TestConstructorFinder {
--- a/jdk/test/java/beans/XMLDecoder/8028054/TestMethodFinder.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/beans/XMLDecoder/8028054/TestMethodFinder.java	Wed Jul 05 22:05:22 2017 +0200
@@ -39,7 +39,7 @@
  *          java.corba
  *          java.xml.bind
  * @compile -XDignore.symbol.file TestMethodFinder.java
- * @run main/othervm -addmods java.activation -addmods java.transaction -addmods java.corba -addmods java.xml.bind TestMethodFinder
+ * @run main/othervm --add-modules=java.activation,java.transaction,java.corba,java.xml.bind TestMethodFinder
  */
 
 public class TestMethodFinder {
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/io/CharArrayReader/OverflowInRead.java	Wed Jul 05 22:05:22 2017 +0200
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/* @test
+ * @bug 8163518
+ * @summary Integer overflow when reading in large buffer
+ * @requires (sun.arch.data.model == "64" & os.maxMemory > 8g)
+ * @run main/othervm -Xmx8g OverflowInRead
+ */
+
+import java.io.CharArrayReader;
+
+public class OverflowInRead {
+    public static void main(String[] args) throws Exception {
+        char[] a = "_123456789_123456789_123456789_123456789"
+                .toCharArray(); // a.length > 33
+        try (CharArrayReader car = new CharArrayReader(a)) {
+            int len1 = 33;
+            char[] buf1 = new char[len1];
+            if (car.read(buf1, 0, len1) != len1)
+                throw new Exception("Expected to read " + len1 + " chars");
+
+            int len2 = Integer.MAX_VALUE - 32;
+            char[] buf2 = new char[len2];
+            int expLen2 = a.length - len1;
+            if (car.read(buf2, 0, len2) != expLen2)
+                throw new Exception("Expected to read " + expLen2 + " chars");
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/io/CharArrayReader/OverflowInSkip.java	Wed Jul 05 22:05:22 2017 +0200
@@ -0,0 +1,51 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/* @test
+ * @bug 8163518
+ * @summary Integer overflow when skipping a lot
+ */
+
+import java.io.CharArrayReader;
+
+public class OverflowInSkip {
+    public static void main(String[] args) throws Exception {
+        char[] a = "_123456789_123456789_123456789_123456789"
+                .toCharArray(); // a.length > 33
+        try (CharArrayReader car = new CharArrayReader(a)) {
+            long small = 33;
+            long big = Long.MAX_VALUE;
+
+            long smallSkip = car.skip(small);
+            if (smallSkip != small)
+                throw new Exception("Expected to skip " + small
+                        + " chars, but skipped " + smallSkip);
+
+            long expSkip = a.length - small;
+            long bigSkip = car.skip(big);
+            if (bigSkip != expSkip)
+                throw new Exception("Expected to skip " + expSkip
+                        + " chars, but skipped " + bigSkip);
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/io/StringBufferInputStream/OverflowInRead.java	Wed Jul 05 22:05:22 2017 +0200
@@ -0,0 +1,49 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/* @test
+ * @bug 8163518
+ * @summary Integer overflow when reading in large buffer
+ * @requires (sun.arch.data.model == "64" & os.maxMemory > 4g)
+ * @run main/othervm -Xmx4g OverflowInRead
+ */
+
+import java.io.StringBufferInputStream;
+
+public class OverflowInRead {
+    public static void main(String[] args) throws Exception {
+        String s = "_123456789_123456789_123456789_123456789"; // s.length() > 33
+        try (StringBufferInputStream sbis = new StringBufferInputStream(s)) {
+            int len1 = 33;
+            byte[] buf1 = new byte[len1];
+            if (sbis.read(buf1, 0, len1) != len1)
+                throw new Exception("Expected to read " + len1 + " bytes");
+
+            int len2 = Integer.MAX_VALUE - 32;
+            byte[] buf2 = new byte[len2];
+            int expLen2 = s.length() - len1;
+            if (sbis.read(buf2, 0, len2) != expLen2)
+                throw new Exception("Expected to read " + expLen2 + " bytes");
+        }
+    }
+}
--- a/jdk/test/java/lang/Class/forName/modules/TestDriver.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/lang/Class/forName/modules/TestDriver.java	Wed Jul 05 22:05:22 2017 +0200
@@ -65,7 +65,7 @@
     public void setup() throws Exception {
         assertTrue(CompilerUtils.compile(
                         MOD_SRC_DIR, MOD_DEST_DIR,
-                        "-modulesourcepath",
+                        "--module-source-path",
                         MOD_SRC_DIR.toString()));
 
         copyDirectories(MOD_DEST_DIR.resolve("m1"), Paths.get("mods1"));
@@ -76,8 +76,8 @@
     public void test() throws Exception {
         String[] options = new String[] {
                 "-cp", TEST_CLASSES,
-                "-mp", MOD_DEST_DIR.toString(),
-                "-addmods", String.join(",", modules),
+                "--module-path", MOD_DEST_DIR.toString(),
+                "--add-modules", String.join(",", modules),
                 "-m", "m2/p2.test.Main"
         };
         runTest(options);
@@ -87,8 +87,8 @@
     public void testUnnamedModule() throws Exception {
         String[] options = new String[] {
                 "-cp", TEST_CLASSES,
-                "-mp", MOD_DEST_DIR.toString(),
-                "-addmods", String.join(",", modules),
+                "--module-path", MOD_DEST_DIR.toString(),
+                "--add-modules", String.join(",", modules),
                 "TestMain"
         };
         runTest(options);
@@ -107,8 +107,8 @@
     @Test
     public void testDeniedClassLoaderAccess() throws Exception {
         String[] options = new String[] {
-                "-mp", MOD_DEST_DIR.toString(),
-                "-addmods", String.join(",", modules),
+                "--module-path", MOD_DEST_DIR.toString(),
+                "--add-modules", String.join(",", modules),
                 "-m", "m3/p3.NoGetClassLoaderAccess"
         };
         assertTrue(executeTestJava(options)
@@ -124,8 +124,8 @@
         String[] options = new String[] {
                 "-Djava.security.manager",
                 "-Djava.security.policy=" + policyFile.toString(),
-                "-mp", MOD_DEST_DIR.toString(),
-                "-addmods", String.join(",", modules),
+                "--module-path", MOD_DEST_DIR.toString(),
+                "--add-modules", String.join(",", modules),
                 "-m", "m3/p3.NoAccess"
         };
         assertTrue(executeTestJava(options)
--- a/jdk/test/java/lang/Class/getDeclaredField/FieldSetAccessibleTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/lang/Class/getDeclaredField/FieldSetAccessibleTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -63,8 +63,8 @@
  *          loads all the classes in the BCL, get their declared fields,
  *          and call setAccessible(false) followed by setAccessible(true);
  * @modules java.base/jdk.internal.module
- * @run main/othervm -Djdk.launcher.addmods=ALL-SYSTEM FieldSetAccessibleTest UNSECURE
- * @run main/othervm -Djdk.launcher.addmods=ALL-SYSTEM FieldSetAccessibleTest SECURE
+ * @run main/othervm --add-modules=ALL-SYSTEM FieldSetAccessibleTest UNSECURE
+ * @run main/othervm --add-modules=ALL-SYSTEM FieldSetAccessibleTest SECURE
  *
  * @author danielfuchs
  */
--- a/jdk/test/java/lang/Class/getResource/ResourcesTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/lang/Class/getResource/ResourcesTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -60,15 +60,15 @@
         compiled = CompilerUtils
             .compile(SRC_DIR,
                      MODS_DIR,
-                     "-modulesourcepath", SRC_DIR.toString());
+                     "--module-source-path", SRC_DIR.toString());
         assertTrue(compiled);
 
-        // javac -mp mods -d classes Main.java
+        // javac --module-path mods -d classes Main.java
         compiled = CompilerUtils
             .compile(Paths.get(TEST_SRC, "Main.java"),
                      CLASSES_DIR,
-                     "-mp", MODS_DIR.toString(),
-                     "-addmods", "m1,m2,m3");
+                     "--module-path", MODS_DIR.toString(),
+                     "--add-modules", "m1,m2,m3");
         assertTrue(compiled);
 
     }
@@ -79,8 +79,8 @@
     public void runTest() throws Exception {
 
         int exitValue
-            = executeTestJava("-mp", MODS_DIR.toString(),
-                              "-addmods", "m1,m2,m3",
+            = executeTestJava("--module-path", MODS_DIR.toString(),
+                              "--add-modules", "m1,m2,m3",
                                "-cp", CLASSES_DIR.toString(),
                               "Main")
                 .outputTo(System.out)
--- a/jdk/test/java/lang/ClassLoader/getResource/modules/ResourcesTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/lang/ClassLoader/getResource/modules/ResourcesTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -56,19 +56,19 @@
     public void compileAll() throws Exception {
         boolean compiled;
 
-        // javac -modulesource mods -d mods src/**
+        // javac --module-source-path mods -d mods src/**
         compiled = CompilerUtils
             .compile(SRC_DIR,
                      MODS_DIR,
-                     "-modulesourcepath", SRC_DIR.toString());
+                     "--module-source-path", SRC_DIR.toString());
         assertTrue(compiled);
 
-        // javac -mp mods -d classes Main.java
+        // javac --module-path mods -d classes Main.java
         compiled = CompilerUtils
             .compile(Paths.get(TEST_SRC, "Main.java"),
                      CLASSES_DIR,
-                     "-mp", MODS_DIR.toString(),
-                     "-addmods", "m1,m2,m3");
+                     "--module-path", MODS_DIR.toString(),
+                     "--add-modules", "m1,m2,m3");
         assertTrue(compiled);
     }
 
@@ -77,8 +77,8 @@
      */
     public void runTest() throws Exception {
         int exitValue
-            = executeTestJava("-mp", MODS_DIR.toString(),
-                              "-addmods", "m1,m2,m3",
+            = executeTestJava("--module-path", MODS_DIR.toString(),
+                              "--add-modules", "m1,m2,m3",
                                "-cp", CLASSES_DIR.toString(),
                               "Main")
                 .outputTo(System.out)
--- a/jdk/test/java/lang/SecurityManager/modules/CustomSecurityManager.sh	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/lang/SecurityManager/modules/CustomSecurityManager.sh	Wed Jul 05 22:05:22 2017 +0200
@@ -51,15 +51,15 @@
 JAVA="$TESTJAVA/bin/java ${TESTVMOPTS}"
 
 mkdir -p mods
-$JAVAC -d mods -modulesourcepath ${TESTSRC} `find ${TESTSRC}/m -name "*.java"`
+$JAVAC -d mods --module-source-path ${TESTSRC} `find ${TESTSRC}/m -name "*.java"`
 
 mkdir -p classes
 $JAVAC -d classes ${TESTSRC}/Test.java
 
-$JAVA -cp classes -mp mods -addmods m \
+$JAVA -cp classes --module-path mods --add-modules m \
     -Djava.security.manager \
     -Djava.security.policy=${TESTSRC}/test.policy Test
-$JAVA -cp classes -mp mods -addmods m \
+$JAVA -cp classes --module-path mods --add-modules m \
     -Djava.security.manager=p.CustomSecurityManager \
     -Djava.security.policy=${TESTSRC}/test.policy Test
 
--- a/jdk/test/java/lang/String/concat/WithSecurityManager.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/lang/String/concat/WithSecurityManager.java	Wed Jul 05 22:05:22 2017 +0200
@@ -38,13 +38,13 @@
  * @run main/othervm -Xverify:all -Djava.lang.invoke.stringConcat=MH_SB_SIZED_EXACT      WithSecurityManager
  * @run main/othervm -Xverify:all -Djava.lang.invoke.stringConcat=MH_INLINE_SIZED_EXACT  WithSecurityManager
  *
- * @run main/othervm -Xverify:all -limitmods java.base WithSecurityManager
- * @run main/othervm -Xverify:all -limitmods java.base -Djava.lang.invoke.stringConcat=BC_SB                  WithSecurityManager
- * @run main/othervm -Xverify:all -limitmods java.base -Djava.lang.invoke.stringConcat=BC_SB_SIZED            WithSecurityManager
- * @run main/othervm -Xverify:all -limitmods java.base -Djava.lang.invoke.stringConcat=MH_SB_SIZED            WithSecurityManager
- * @run main/othervm -Xverify:all -limitmods java.base -Djava.lang.invoke.stringConcat=BC_SB_SIZED_EXACT      WithSecurityManager
- * @run main/othervm -Xverify:all -limitmods java.base -Djava.lang.invoke.stringConcat=MH_SB_SIZED_EXACT      WithSecurityManager
- * @run main/othervm -Xverify:all -limitmods java.base -Djava.lang.invoke.stringConcat=MH_INLINE_SIZED_EXACT  WithSecurityManager
+ * @run main/othervm -Xverify:all --limit-modules=java.base WithSecurityManager
+ * @run main/othervm -Xverify:all --limit-modules=java.base -Djava.lang.invoke.stringConcat=BC_SB                  WithSecurityManager
+ * @run main/othervm -Xverify:all --limit-modules=java.base -Djava.lang.invoke.stringConcat=BC_SB_SIZED            WithSecurityManager
+ * @run main/othervm -Xverify:all --limit-modules=java.base -Djava.lang.invoke.stringConcat=MH_SB_SIZED            WithSecurityManager
+ * @run main/othervm -Xverify:all --limit-modules=java.base -Djava.lang.invoke.stringConcat=BC_SB_SIZED_EXACT      WithSecurityManager
+ * @run main/othervm -Xverify:all --limit-modules=java.base -Djava.lang.invoke.stringConcat=MH_SB_SIZED_EXACT      WithSecurityManager
+ * @run main/othervm -Xverify:all --limit-modules=java.base -Djava.lang.invoke.stringConcat=MH_INLINE_SIZED_EXACT  WithSecurityManager
 */
 public class WithSecurityManager {
     public static void main(String[] args) throws Throwable {
--- a/jdk/test/java/lang/instrument/MakeJAR2.sh	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/lang/instrument/MakeJAR2.sh	Wed Jul 05 22:05:22 2017 +0200
@@ -87,7 +87,7 @@
 cd ..
 
 ${JAVAC} ${TESTJAVACOPTS} ${TESTTOOLVMOPTS} \
-    -XaddExports:java.base/jdk.internal.org.objectweb.asm=ALL-UNNAMED ${AGENT}.java asmlib/*.java
+    --add-exports java.base/jdk.internal.org.objectweb.asm=ALL-UNNAMED ${AGENT}.java asmlib/*.java
 ${JAVAC} ${TESTJAVACOPTS} ${TESTTOOLVMOPTS} -classpath .${PATHSEP}bootpath ${APP}.java
 
 echo "Manifest-Version: 1.0"    >  ${AGENT}.mf
--- a/jdk/test/java/lang/invoke/modules/ModuleAccessControlTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/lang/invoke/modules/ModuleAccessControlTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -60,7 +60,7 @@
         for (String mn : modules) {
             Path msrc = SRC_DIR.resolve(mn);
             assertTrue(CompilerUtils
-                .compile(msrc, MODS_DIR, "-modulesourcepath", SRC_DIR.toString()));
+                .compile(msrc, MODS_DIR, "--module-source-path", SRC_DIR.toString()));
         }
     }
 
@@ -69,7 +69,7 @@
      */
     @Test
     public void runTest() throws Exception {
-        int exitValue = executeTestJava("-mp", MODS_DIR.toString(),
+        int exitValue = executeTestJava("--module-path", MODS_DIR.toString(),
                                         "-m", "m1/p1.Main")
                 .outputTo(System.out)
                 .errorTo(System.out)
--- a/jdk/test/java/lang/reflect/Layer/LayerAndLoadersTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/lang/reflect/Layer/LayerAndLoadersTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -63,9 +63,9 @@
     @BeforeTest
     public void setup() throws Exception {
 
-        // javac -d mods -modulesourcepath src src/**
+        // javac -d mods --module-source-path src src/**
         assertTrue(CompilerUtils.compile(SRC_DIR, MODS_DIR,
-                "-modulesourcepath", SRC_DIR.toString()));
+                "--module-source-path", SRC_DIR.toString()));
     }
 
 
--- a/jdk/test/java/lang/reflect/Layer/src/m1/module-info.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/lang/reflect/Layer/src/m1/module-info.java	Wed Jul 05 22:05:22 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/jdk/test/java/lang/reflect/Module/AddExportsTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/lang/reflect/Module/AddExportsTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -23,29 +23,44 @@
 
 /**
  * @test
- * @modules java.desktop
- * @run main/othervm -XaddExports:java.desktop/sun.awt=java.base AddExportsTest
- * @run main/othervm -XaddExports:java.desktop/sun.awt=ALL-UNNAMED AddExportsTest
+ * @modules java.base/jdk.internal.misc
+ *          java.desktop
+ * @run main/othervm --add-exports=java.desktop/sun.awt=java.base AddExportsTest
+ * @run main/othervm --add-exports=java.desktop/sun.awt=ALL-UNNAMED AddExportsTest
  * @summary Test Module isExported methods with exports changed by -AddExportsTest
  */
 
 import java.lang.reflect.Layer;
 import java.lang.reflect.Module;
 import java.util.Optional;
+import java.util.stream.Stream;
+
+import jdk.internal.misc.VM;
 
 public class AddExportsTest {
+    /*
+     * jtreg sets -Dtest.modules system property to the internal APIs
+     * specified at @modules tag.  The test will exclude --add-exports set
+     * for @modules.
+     */
+    private static final String TEST_MODULES = System.getProperty("test.modules");
 
     public static void main(String[] args) {
 
-        String addExports = System.getProperty("jdk.launcher.addexports.0");
-        assertTrue(addExports != null, "Expected to be run with -XaddExports");
+        Optional<String> oaddExports = Stream.of(VM.getRuntimeArguments())
+            .filter(arg -> arg.startsWith("--add-exports="))
+            .filter(arg -> !arg.equals("--add-exports=" + TEST_MODULES + "=ALL-UNNAMED"))
+            .map(arg -> arg.substring("--add-exports=".length(), arg.length()))
+            .findFirst();
+
+        assertTrue(oaddExports.isPresent());
 
         Layer bootLayer = Layer.boot();
 
         Module unnamedModule = AddExportsTest.class.getModule();
         assertFalse(unnamedModule.isNamed());
 
-        for (String expr : addExports.split(",")) {
+        for (String expr : oaddExports.get().split(",")) {
 
             String[] s = expr.split("=");
             assertTrue(s.length == 2);
--- a/jdk/test/java/lang/reflect/Module/access/AccessTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/lang/reflect/Module/access/AccessTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -72,8 +72,8 @@
      */
     public void runTest() throws Exception {
         int exitValue
-            = executeTestJava("-mp", MODS_DIR.toString(),
-                              "-addmods", "target",
+            = executeTestJava("--module-path", MODS_DIR.toString(),
+                              "--add-modules", "target",
                               "-m", "test/test.Main")
                 .outputTo(System.out)
                 .errorTo(System.out)
--- a/jdk/test/java/lang/reflect/Proxy/ProxyClassAccessTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/lang/reflect/Proxy/ProxyClassAccessTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -64,7 +64,7 @@
     public void compileAll() throws Exception {
         for (String mn : modules) {
             Path msrc = SRC_DIR.resolve(mn);
-            assertTrue(CompilerUtils.compile(msrc, MODS_DIR, "-modulesourcepath", SRC_DIR.toString()));
+            assertTrue(CompilerUtils.compile(msrc, MODS_DIR, "--module-source-path", SRC_DIR.toString()));
         }
     }
 
@@ -73,7 +73,7 @@
      */
     @Test
     public void runTest() throws Exception {
-        int exitValue = executeTestJava("-mp", MODS_DIR.toString(),
+        int exitValue = executeTestJava("--module-path", MODS_DIR.toString(),
                                         "-m", "test/jdk.test.ProxyClassAccess")
                             .outputTo(System.out)
                             .errorTo(System.out)
--- a/jdk/test/java/lang/reflect/Proxy/ProxyLayerTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/lang/reflect/Proxy/ProxyLayerTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -65,7 +65,7 @@
     public void compileAll() throws Exception {
         for (String mn : modules) {
             Path msrc = SRC_DIR.resolve(mn);
-            assertTrue(CompilerUtils.compile(msrc, MODS_DIR, "-modulesourcepath", SRC_DIR.toString()));
+            assertTrue(CompilerUtils.compile(msrc, MODS_DIR, "--module-source-path", SRC_DIR.toString()));
         }
     }
 
--- a/jdk/test/java/lang/reflect/Proxy/ProxyModuleMapping.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/lang/reflect/Proxy/ProxyModuleMapping.java	Wed Jul 05 22:05:22 2017 +0200
@@ -38,7 +38,7 @@
         Module unnamed = ld.getUnnamedModule();
         new ProxyModuleMapping(unnamed, Runnable.class).test();
 
-        // unnamed module gets access to sun.invoke package (e.g. via -XaddExports)
+        // unnamed module gets access to sun.invoke package (e.g. via --add-exports)
         new ProxyModuleMapping(sun.invoke.WrapperInstance.class).test();
 
         Class<?> modulePrivateIntf = Class.forName("sun.net.ProgressListener");
--- a/jdk/test/java/lang/reflect/Proxy/ProxyTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/lang/reflect/Proxy/ProxyTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -61,7 +61,7 @@
     public void compileAll() throws Exception {
         for (String mn : modules) {
             Path msrc = SRC_DIR.resolve(mn);
-            assertTrue(CompilerUtils.compile(msrc, MODS_DIR, "-modulesourcepath", SRC_DIR.toString()));
+            assertTrue(CompilerUtils.compile(msrc, MODS_DIR, "--module-source-path", SRC_DIR.toString()));
         }
     }
 
@@ -71,7 +71,7 @@
     @Test
     public void runTest() throws Exception {
         int exitValue = executeTestJava("-cp", CPATH_DIR.toString(),
-                                        "-mp", MODS_DIR.toString(),
+                                        "--module-path", MODS_DIR.toString(),
                                         "-m", "test/jdk.test.Main")
                             .outputTo(System.out)
                             .errorTo(System.out)
--- a/jdk/test/java/net/Authenticator/B4933582.sh	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/net/Authenticator/B4933582.sh	Wed Jul 05 22:05:22 2017 +0200
@@ -44,7 +44,7 @@
     ;;
 esac
 
-EXTRAOPTS="-XaddExports:java.base/sun.net.www=ALL-UNNAMED -XaddExports:java.base/sun.net.www.protocol.http=ALL-UNNAMED"
+EXTRAOPTS="--add-exports java.base/sun.net.www=ALL-UNNAMED --add-exports java.base/sun.net.www.protocol.http=ALL-UNNAMED"
 export EXTRAOPTS
 
 ${COMPILEJAVA}${FS}bin${FS}javac ${TESTJAVACOPTS} ${TESTTOOLVMOPTS} ${EXTRAOPTS} -d . \
--- a/jdk/test/java/net/ProxySelector/B8035158.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/net/ProxySelector/B8035158.java	Wed Jul 05 22:05:22 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -22,7 +22,7 @@
  */
 /*
  * @test
- * @bug 8035158
+ * @bug 8035158 8145732
  * @run main/othervm B8035158
  */
 
@@ -94,6 +94,8 @@
                 false));
         t.add(new TestCase("google.com|google.ie", "http://google.ie",
                 false));
+        t.add(new TestCase("google.com|google.com|google.ie",
+                "http://google.ie", false));
 
         t.add(new TestCase("google.com|bing.com|yahoo.com",
                 "http://127.0.0.1", false));
--- a/jdk/test/java/net/SocketOption/OptionsTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/net/SocketOption/OptionsTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -26,7 +26,7 @@
  * @bug 8036979 8072384 8044773
  * @run main/othervm -Xcheck:jni OptionsTest
  * @run main/othervm -Xcheck:jni -Djava.net.preferIPv4Stack=true OptionsTest
- * @run main/othervm -limitmods java.base OptionsTest
+ * @run main/othervm --limit-modules=java.base OptionsTest
  */
 
 import java.lang.reflect.Method;
--- a/jdk/test/java/net/SocketOption/UnsupportedOptionsTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/net/SocketOption/UnsupportedOptionsTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -33,7 +33,7 @@
  * @summary Test checks that UnsupportedOperationException for unsupported
  * SOCKET_OPTIONS is thrown by both getOption() and setOption() methods.
  * @run main UnsupportedOptionsTest
- * @run main/othervm -limitmods java.base UnsupportedOptionsTest
+ * @run main/othervm --limit-modules=java.base UnsupportedOptionsTest
  */
 
 public class UnsupportedOptionsTest {
--- a/jdk/test/java/net/httpclient/http2/HpackDriver.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/net/httpclient/http2/HpackDriver.java	Wed Jul 05 22:05:22 2017 +0200
@@ -29,12 +29,12 @@
  * @compile/module=java.httpclient sun/net/httpclient/hpack/SpecHelper.java
  * @compile/module=java.httpclient sun/net/httpclient/hpack/TestHelper.java
  * @compile/module=java.httpclient sun/net/httpclient/hpack/BuffersTestingKit.java
- * @run testng/othervm -XaddReads:java.httpclient=ALL-UNNAMED java.httpclient/sun.net.httpclient.hpack.BinaryPrimitivesTest
- * @run testng/othervm -XaddReads:java.httpclient=ALL-UNNAMED java.httpclient/sun.net.httpclient.hpack.CircularBufferTest
- * @run testng/othervm -XaddReads:java.httpclient=ALL-UNNAMED java.httpclient/sun.net.httpclient.hpack.DecoderTest
- * @run testng/othervm -XaddReads:java.httpclient=ALL-UNNAMED java.httpclient/sun.net.httpclient.hpack.EncoderTest
- * @run testng/othervm -XaddReads:java.httpclient=ALL-UNNAMED java.httpclient/sun.net.httpclient.hpack.HeaderTableTest
- * @run testng/othervm -XaddReads:java.httpclient=ALL-UNNAMED java.httpclient/sun.net.httpclient.hpack.HuffmanTest
- * @run testng/othervm -XaddReads:java.httpclient=ALL-UNNAMED java.httpclient/sun.net.httpclient.hpack.TestHelper
+ * @run testng/othervm java.httpclient/sun.net.httpclient.hpack.BinaryPrimitivesTest
+ * @run testng/othervm java.httpclient/sun.net.httpclient.hpack.CircularBufferTest
+ * @run testng/othervm java.httpclient/sun.net.httpclient.hpack.DecoderTest
+ * @run testng/othervm java.httpclient/sun.net.httpclient.hpack.EncoderTest
+ * @run testng/othervm java.httpclient/sun.net.httpclient.hpack.HeaderTableTest
+ * @run testng/othervm java.httpclient/sun.net.httpclient.hpack.HuffmanTest
+ * @run testng/othervm java.httpclient/sun.net.httpclient.hpack.TestHelper
  */
 public class HpackDriver { }
--- a/jdk/test/java/nio/channels/DatagramChannel/SocketOptionTests.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/nio/channels/DatagramChannel/SocketOptionTests.java	Wed Jul 05 22:05:22 2017 +0200
@@ -25,7 +25,7 @@
  * @bug 4640544 8044773
  * @summary Unit test for setOption/getOption/options methods
  * @run main SocketOptionTests
- * @run main/othervm -limitmods java.base SocketOptionTests
+ * @run main/othervm --limit-modules=java.base SocketOptionTests
  */
 
 import java.nio.*;
--- a/jdk/test/java/nio/channels/Selector/RacyDeregister.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/nio/channels/Selector/RacyDeregister.java	Wed Jul 05 22:05:22 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -40,6 +40,11 @@
  */
 public class RacyDeregister {
 
+    // FIXME: numOuterLoopIterations should be reverted to the hard-coded value
+    // 15 when JDK-8161083 is resolved as either a bug or a non-issue.
+    static final int numOuterLoopIterations =
+        System.getProperty("os.name").startsWith("Windows") ? 150 : 15;
+
     static boolean notified;
     static final Object selectorLock = new Object();
     static final Object notifyLock = new Object();
@@ -77,7 +82,7 @@
 
             public void run() {
                 try {
-                    for (int k = 0; k < 15; k++) {
+                    for (int k = 0; k < numOuterLoopIterations; k++) {
                         for (int i = 0; i < 10000; i++) {
                             synchronized (notifyLock) {
                                 synchronized (selectorLock) {
@@ -94,6 +99,17 @@
                                     }
                                     long endTime = System.currentTimeMillis();
                                     if (endTime - beginTime > 5000) {
+                                        for (int j = 0; j < 60; j++) {
+                                            Thread.sleep(1000);
+                                            if (notified) {
+                                                long t =
+                                                    System.currentTimeMillis();
+                                                System.out.printf
+                                                    ("Notified after %d ms%n",
+                                                     t - beginTime);
+                                                break;
+                                            }
+                                        }
                                         succTermination = false;
                                         // wake up main thread doing select()
                                         sel.wakeup();
--- a/jdk/test/java/nio/channels/ServerSocketChannel/SocketOptionTests.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/nio/channels/ServerSocketChannel/SocketOptionTests.java	Wed Jul 05 22:05:22 2017 +0200
@@ -26,7 +26,7 @@
  * @summary Unit test for ServerSocketChannel setOption/getOption/options
  *          methods.
  * @run main SocketOptionTests
- * @run main/othervm -limitmods java.base SocketOptionTests
+ * @run main/othervm --limit-modules=java.base SocketOptionTests
  */
 
 import java.nio.*;
--- a/jdk/test/java/nio/channels/SocketChannel/SocketOptionTests.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/nio/channels/SocketChannel/SocketOptionTests.java	Wed Jul 05 22:05:22 2017 +0200
@@ -26,7 +26,7 @@
  * @summary Unit test to check SocketChannel setOption/getOption/options
  *          methods.
  * @run main SocketOptionTests
- * @run main/othervm -limitmods java.base SocketOptionTests
+ * @run main/othervm --limit-modules=java.base SocketOptionTests
  */
 
 import java.nio.*;
--- a/jdk/test/java/nio/channels/spi/SelectorProvider/inheritedChannel/run_tests.sh	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/nio/channels/spi/SelectorProvider/inheritedChannel/run_tests.sh	Wed Jul 05 22:05:22 2017 +0200
@@ -109,7 +109,7 @@
 
 go() {
     echo ''
-    sh -xc "$JAVA ${TESTVMOPTS} -XaddExports:java.base/sun.nio.ch=ALL-UNNAMED $DFLAG \
+    sh -xc "$JAVA ${TESTVMOPTS} --add-exports java.base/sun.nio.ch=ALL-UNNAMED $DFLAG \
         $1 $2 $3 $4 $5 $6 $7 $8" 2>&1
     if [ $? != 0 ]; then failures=`expr $failures + 1`; fi
 }
--- a/jdk/test/java/nio/file/Files/probeContentType/Basic.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/nio/file/Files/probeContentType/Basic.java	Wed Jul 05 22:05:22 2017 +0200
@@ -95,7 +95,7 @@
         return 0;
     }
 
-    static int checkContentTypes(String[] extensions, String[] expectedTypes)
+    static int checkContentTypes(String[] extensions, String[][] expectedTypes)
         throws IOException {
         if (extensions.length != expectedTypes.length) {
             System.err.println("Parameter array lengths differ");
@@ -113,9 +113,24 @@
                             + " cannot be determined");
                     failures++;
                 } else {
-                    if (!type.equals(expectedTypes[i])) {
-                        System.err.println("Content type: " + type
-                                + "; expected: " + expectedTypes[i]);
+                    boolean isTypeFound = false;
+                    for (String s : expectedTypes[i]) {
+                        if (type.equals(s)) {
+                            isTypeFound = true;
+                            break;
+                        }
+                    }
+                    if (!isTypeFound) {
+                        System.err.printf("Content type: %s; expected: ", type);
+                        int j = 0;
+                        for (String s : expectedTypes[i]) {
+                            if (j++ == 0) {
+                                System.err.printf("%s", s);
+                            } else {
+                                System.err.printf(", or %s", s);
+                            }
+                        }
+                        System.err.println();
                         failures++;
                     }
                 }
@@ -159,11 +174,24 @@
 
         // Verify that certain media extensions are mapped to the correct type.
         String[] extensions = new String[]{
-            "aac", "flac", "jpg", "mp3", "mp4", "pdf", "png", "webm"
+            "aac",
+            "flac",
+            "jpg",
+            "mp3",
+            "mp4",
+            "pdf",
+            "png",
+            "webm"
         };
-        String[] expectedTypes = new String[]{
-            "audio/aac", "audio/flac", "image/jpeg", "audio/mpeg",
-            "video/mp4", "application/pdf", "image/png", "video/webm"
+        String[][] expectedTypes = new String[][] {
+            {"audio/aac", "audio/x-aac"},
+            {"audio/flac", "audio/x-flac"},
+            {"image/jpeg"},
+            {"audio/mpeg"},
+            {"video/mp4"},
+            {"application/pdf"},
+            {"image/png"},
+            {"video/webm"}
         };
         failures += checkContentTypes(extensions, expectedTypes);
 
--- a/jdk/test/java/rmi/activation/Activatable/extLoadedImpl/ext.sh	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/rmi/activation/Activatable/extLoadedImpl/ext.sh	Wed Jul 05 22:05:22 2017 +0200
@@ -52,9 +52,9 @@
 $COMPILEJAVA/bin/jar ${TESTTOOLVMOPTS} cf ext/ext.jar -C $TESTCLASSES ExtLoadedImpl.class -C $TESTCLASSES ExtLoadedImpl_Stub.class -C $TESTCLASSES CheckLoader.class
 
 TESTVMOPTS="${TESTVMOPTS} \
- -XaddExports:java.rmi/sun.rmi.registry=ALL-UNNAMED \
- -XaddExports:java.rmi/sun.rmi.server=ALL-UNNAMED \
- -XaddExports:java.rmi/sun.rmi.transport=ALL-UNNAMED \
- -XaddExports:java.rmi/sun.rmi.transport.tcp=ALL-UNNAMED"
+ --add-exports java.rmi/sun.rmi.registry=ALL-UNNAMED \
+ --add-exports java.rmi/sun.rmi.server=ALL-UNNAMED \
+ --add-exports java.rmi/sun.rmi.transport=ALL-UNNAMED \
+ --add-exports java.rmi/sun.rmi.transport.tcp=ALL-UNNAMED"
 $TESTJAVA/bin/java ${TESTVMOPTS} -cp classes -Dtest.src=$TESTSRC -Dtest.classes=$TESTCLASSES -Djava.security.policy=$TESTSRC/security.policy -Djava.ext.dirs=ext ExtLoadedImplTest
 
--- a/jdk/test/java/rmi/activation/ActivationGroup/downloadActivationGroup/DownloadActivationGroup.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/rmi/activation/ActivationGroup/downloadActivationGroup/DownloadActivationGroup.java	Wed Jul 05 22:05:22 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2015, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -24,7 +24,6 @@
 /*
  * @test
  * @bug 4510355
- * @key intermittent
  * @summary ActivationGroup implementations cannot be downloaded by default;
  * Creates a custom activation group without setting a security manager
  * in activation group's descriptor.  The custom activation group
@@ -140,10 +139,10 @@
             CommandEnvironment cmd = new ActivationGroupDesc.CommandEnvironment(
                     null,
                     new String[] {
-                        "-XaddExports:java.rmi/sun.rmi.registry=ALL-UNNAMED",
-                        "-XaddExports:java.rmi/sun.rmi.server=ALL-UNNAMED",
-                        "-XaddExports:java.rmi/sun.rmi.transport=ALL-UNNAMED",
-                        "-XaddExports:java.rmi/sun.rmi.transport.tcp=ALL-UNNAMED" });
+                        "--add-exports=java.rmi/sun.rmi.registry=ALL-UNNAMED",
+                        "--add-exports=java.rmi/sun.rmi.server=ALL-UNNAMED",
+                        "--add-exports=java.rmi/sun.rmi.transport=ALL-UNNAMED",
+                        "--add-exports=java.rmi/sun.rmi.transport.tcp=ALL-UNNAMED" });
 
             ActivationGroupDesc groupDesc =
                 new ActivationGroupDesc("MyActivationGroupImpl",
--- a/jdk/test/java/rmi/activation/ActivationSystem/stubClassesPermitted/StubClassesPermitted.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/rmi/activation/ActivationSystem/stubClassesPermitted/StubClassesPermitted.java	Wed Jul 05 22:05:22 2017 +0200
@@ -121,11 +121,11 @@
             System.err.println("Create activation group, in a new VM");
             CommandEnvironment cmd = new ActivationGroupDesc.CommandEnvironment(null,
                     new String[] {
-                        "-XaddExports:java.base/sun.security.provider=ALL-UNNAMED",
-                        "-XaddExports:java.rmi/sun.rmi.registry=ALL-UNNAMED",
-                        "-XaddExports:java.rmi/sun.rmi.server=ALL-UNNAMED",
-                        "-XaddExports:java.rmi/sun.rmi.transport=ALL-UNNAMED",
-                        "-XaddExports:java.rmi/sun.rmi.transport.tcp=ALL-UNNAMED" });
+                        "--add-exports=java.base/sun.security.provider=ALL-UNNAMED",
+                        "--add-exports=java.rmi/sun.rmi.registry=ALL-UNNAMED",
+                        "--add-exports=java.rmi/sun.rmi.server=ALL-UNNAMED",
+                        "--add-exports=java.rmi/sun.rmi.transport=ALL-UNNAMED",
+                        "--add-exports=java.rmi/sun.rmi.transport.tcp=ALL-UNNAMED" });
 
             ActivationGroupDesc groupDesc =
                 new ActivationGroupDesc(p, cmd);
--- a/jdk/test/java/rmi/activation/rmidViaInheritedChannel/InheritedChannelNotServerSocket.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/rmi/activation/rmidViaInheritedChannel/InheritedChannelNotServerSocket.java	Wed Jul 05 22:05:22 2017 +0200
@@ -106,7 +106,7 @@
             rmid = RMID.createRMID(System.out, System.err, true, true,
                                    TestLibrary.INHERITEDCHANNELNOTSERVERSOCKET_ACTIVATION_PORT);
             rmid.addOptions(
-                "-XaddExports:java.base/sun.nio.ch=ALL-UNNAMED",
+                "--add-exports=java.base/sun.nio.ch=ALL-UNNAMED",
                 "-Djava.nio.channels.spi.SelectorProvider=InheritedChannelNotServerSocket$SP");
             rmid.start();
 
--- a/jdk/test/java/rmi/activation/rmidViaInheritedChannel/RmidViaInheritedChannel.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/rmi/activation/rmidViaInheritedChannel/RmidViaInheritedChannel.java	Wed Jul 05 22:05:22 2017 +0200
@@ -93,7 +93,7 @@
             rmid = RMID.createRMID(System.out, System.err, true, false,
                                    TestLibrary.RMIDVIAINHERITEDCHANNEL_ACTIVATION_PORT);
             rmid.addOptions(
-                "-XaddExports:java.base/sun.nio.ch=ALL-UNNAMED",
+                "--add-exports=java.base/sun.nio.ch=ALL-UNNAMED",
                 "-Djava.nio.channels.spi.SelectorProvider=RmidViaInheritedChannel$RmidSelectorProvider");
             if (System.getProperty("os.name").startsWith("Windows") &&
                 System.getProperty("os.version").startsWith("5."))
--- a/jdk/test/java/rmi/module/ModuleTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/rmi/module/ModuleTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -97,8 +97,8 @@
      */
     @Test
     public void testAllInModule() throws Exception {
-        assertEquals(executeTestJava("-mp", pathJoin(MTEST_JAR, CLIENT_JAR, SERVER_JAR),
-                "-addmods", "mclient,mserver",
+        assertEquals(executeTestJava("--module-path", pathJoin(MTEST_JAR, CLIENT_JAR, SERVER_JAR),
+                "--add-modules", "mclient,mserver",
                 "-m", "mtest/" + DUMMY_MAIN)
                 .outputTo(System.out)
                 .errorTo(System.out)
@@ -113,7 +113,7 @@
      */
     @Test
     public void testAppInModule() throws Exception {
-        assertEquals(executeTestJava("-mp", MTEST_JAR,
+        assertEquals(executeTestJava("--module-path", MTEST_JAR,
                 "-cp", pathJoin(CLIENT_JAR, SERVER_JAR),
                 "-m", "mtest/" + DUMMY_MAIN)
                 .outputTo(System.out)
@@ -129,8 +129,8 @@
      */
     @Test
     public void testAppInUnnamedModule() throws Exception {
-        assertEquals(executeTestJava("-mp", pathJoin(CLIENT_JAR, SERVER_JAR),
-                "-addmods", "mclient,mserver",
+        assertEquals(executeTestJava("--module-path", pathJoin(CLIENT_JAR, SERVER_JAR),
+                "--add-modules", "mclient,mserver",
                 "-cp", MTEST_JAR,
                 DUMMY_MAIN)
                 .outputTo(System.out)
@@ -146,8 +146,8 @@
      */
     @Test
     public void testClientInUnamedModule() throws Exception {
-        assertEquals(executeTestJava("-mp", pathJoin(MTEST_JAR, SERVER_JAR),
-                "-addmods", "mserver",
+        assertEquals(executeTestJava("--module-path", pathJoin(MTEST_JAR, SERVER_JAR),
+                "--add-modules", "mserver",
                 "-cp", CLIENT_JAR,
                 "-m", "mtest/" + DUMMY_MAIN)
                 .outputTo(System.out)
--- a/jdk/test/java/rmi/registry/readTest/readTest.sh	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/rmi/registry/readTest/readTest.sh	Wed Jul 05 22:05:22 2017 +0200
@@ -99,10 +99,10 @@
 esac
 # trailing / after code base is important for rmi codebase property.
 TESTVMOPTS="${TESTVMOPTS} \
- -XaddExports:java.rmi/sun.rmi.registry=ALL-UNNAMED \
- -XaddExports:java.rmi/sun.rmi.server=ALL-UNNAMED \
- -XaddExports:java.rmi/sun.rmi.transport=ALL-UNNAMED \
- -XaddExports:java.rmi/sun.rmi.transport.tcp=ALL-UNNAMED"
+ --add-exports java.rmi/sun.rmi.registry=ALL-UNNAMED \
+ --add-exports java.rmi/sun.rmi.server=ALL-UNNAMED \
+ --add-exports java.rmi/sun.rmi.transport=ALL-UNNAMED \
+ --add-exports java.rmi/sun.rmi.transport.tcp=ALL-UNNAMED"
 ${TESTJAVA}${FS}bin${FS}java ${TESTVMOPTS} -cp $TEST_CLASSPATH ${ARGS} -Djava.rmi.server.codebase=${FILEURL}$CODEBASE/ readTest > OUT.TXT 2>&1 &
 TEST_PID=$!
 #bulk of testcase - let it run for a while
--- a/jdk/test/java/rmi/transport/checkFQDN/CheckFQDN.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/rmi/transport/checkFQDN/CheckFQDN.java	Wed Jul 05 22:05:22 2017 +0200
@@ -123,10 +123,10 @@
                                     propOption + property +
                                     equal +
                                     propertyValue + extraProp +
-                                    " -XaddExports:java.rmi/sun.rmi.registry=ALL-UNNAMED" +
-                                    " -XaddExports:java.rmi/sun.rmi.server=ALL-UNNAMED" +
-                                    " -XaddExports:java.rmi/sun.rmi.transport=ALL-UNNAMED" +
-                                    " -XaddExports:java.rmi/sun.rmi.transport.tcp=ALL-UNNAMED" +
+                                    " --add-exports=java.rmi/sun.rmi.registry=ALL-UNNAMED" +
+                                    " --add-exports=java.rmi/sun.rmi.server=ALL-UNNAMED" +
+                                    " --add-exports=java.rmi/sun.rmi.transport=ALL-UNNAMED" +
+                                    " --add-exports=java.rmi/sun.rmi.transport.tcp=ALL-UNNAMED" +
                                     " -Drmi.registry.port=" +
                                     REGISTRY_PORT,
                                     "");
--- a/jdk/test/java/rmi/transport/dgcDeadLock/DGCDeadLock.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/rmi/transport/dgcDeadLock/DGCDeadLock.java	Wed Jul 05 22:05:22 2017 +0200
@@ -75,10 +75,10 @@
         try {
             String options = " -Djava.security.policy=" +
                 TestParams.defaultPolicy +
-                " -XaddExports:java.rmi/sun.rmi.registry=ALL-UNNAMED" +
-                " -XaddExports:java.rmi/sun.rmi.server=ALL-UNNAMED" +
-                " -XaddExports:java.rmi/sun.rmi.transport=ALL-UNNAMED" +
-                " -XaddExports:java.rmi/sun.rmi.transport.tcp=ALL-UNNAMED" +
+                " --add-exports java.rmi/sun.rmi.registry=ALL-UNNAMED" +
+                " --add-exports java.rmi/sun.rmi.server=ALL-UNNAMED" +
+                " --add-exports java.rmi/sun.rmi.transport=ALL-UNNAMED" +
+                " --add-exports java.rmi/sun.rmi.transport.tcp=ALL-UNNAMED" +
                 " -Djava.rmi.dgc.leaseValue=500000" +
                 "  -Dsun.rmi.dgc.checkInterval=" +
                 (HOLD_TARGET_TIME - 5000) +
--- a/jdk/test/java/security/Provider/SecurityProviderModularTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/security/Provider/SecurityProviderModularTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -317,7 +317,7 @@
         vmArgs.put("-Duser.language=", "en");
         vmArgs.put("-Duser.region=", "US");
         if (addModName != null && sModuletype == MODULE_TYPE.AUTO) {
-            vmArgs.put("-addmods ", addModName);
+            vmArgs.put("--add-modules=", addModName);
         }
         // If mechanism selected to find the provider through
         // Security.getProvider() then use providerName/ProviderClassName based
--- a/jdk/test/java/security/modules/ModularTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/security/modules/ModularTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -137,7 +137,7 @@
         final StringJoiner command = new StringJoiner(SPACE, SPACE, SPACE);
         vmArgs.forEach((key, value) -> command.add(key + value));
         if (modulePath != null) {
-            command.add("-mp").add(modulePath.toFile().getCanonicalPath());
+            command.add("--module-path").add(modulePath.toFile().getCanonicalPath());
         }
         if (classPath != null && classPath.length() > 0) {
             command.add("-cp").add(classPath);
--- a/jdk/test/java/security/testlibrary/Proc.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/security/testlibrary/Proc.java	Wed Jul 05 22:05:22 2017 +0200
@@ -25,19 +25,19 @@
 import java.io.File;
 import java.io.IOException;
 import java.io.InputStreamReader;
-import java.net.URL;
-import java.net.URLClassLoader;
 import java.nio.file.Files;
 import java.nio.file.Path;
 import java.nio.file.Paths;
 import java.security.Permission;
 import java.util.ArrayList;
+import java.util.Arrays;
 import java.util.Base64;
 import java.util.Collections;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.Map.Entry;
+import java.util.stream.Stream;
 
 /**
  * This is a test library that makes writing a Java test that spawns multiple
@@ -184,12 +184,9 @@
                         "java").getPath());
         }
 
-        int n = 0;
-        String addexports;
-        while ((addexports = System.getProperty("jdk.launcher.addexports." + n)) != null) {
-            prop("jdk.launcher.addexports." + n, addexports);
-            n++;
-        }
+        Stream.of(jdk.internal.misc.VM.getRuntimeArguments())
+            .filter(arg -> arg.startsWith("--add-exports="))
+            .forEach(cmd::add);
 
         Collections.addAll(cmd, splitProperty("test.vm.opts"));
         Collections.addAll(cmd, splitProperty("test.java.opts"));
--- a/jdk/test/java/util/Calendar/GenericTimeZoneNamesTest.sh	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/util/Calendar/GenericTimeZoneNamesTest.sh	Wed Jul 05 22:05:22 2017 +0200
@@ -31,7 +31,7 @@
 # This test is locale data-dependent and assumes that both JRE and CLDR
 # have the same geneic time zone names in English.
 
-EXTRAOPTS="-XaddExports:java.base/sun.util.locale.provider=ALL-UNNAMED"
+EXTRAOPTS="--add-exports java.base/sun.util.locale.provider=ALL-UNNAMED"
 STATUS=0
 echo "Locale providers: default"
 if ! ${TESTJAVA}/bin/java -esa ${TESTVMOPTS} ${EXTRAOPTS} -cp "${TESTCLASSES}" GenericTimeZoneNamesTest en-US; then
--- a/jdk/test/java/util/Formatter/Basic.sh	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/util/Formatter/Basic.sh	Wed Jul 05 22:05:22 2017 +0200
@@ -23,7 +23,7 @@
 
 #
 
-EXTRAOPTS="-XaddExports:java.base/jdk.internal.math=ALL-UNNAMED"
+EXTRAOPTS="--add-exports java.base/jdk.internal.math=ALL-UNNAMED"
 ${COMPILEJAVA}/bin/javac ${TESTJAVACOPTS} ${TESTTOOLVMOPTS} ${EXTRAOPTS} -cp ${TESTSRC} -d . \
     ${TESTSRC}/Basic.java
 
--- a/jdk/test/java/util/Locale/LocaleProviders.sh	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/util/Locale/LocaleProviders.sh	Wed Jul 05 22:05:22 2017 +0200
@@ -122,8 +122,8 @@
 tznp8013086
 EOF
 
-EXTRAOPTS="-XaddExports:java.base/sun.util.locale=ALL-UNNAMED \
- -XaddExports:java.base/sun.util.locale.provider=ALL-UNNAMED"
+EXTRAOPTS="--add-exports java.base/sun.util.locale=ALL-UNNAMED \
+ --add-exports java.base/sun.util.locale.provider=ALL-UNNAMED"
 
 ${COMPILEJAVA}${FS}bin${FS}javac ${TESTJAVACOPTS} ${TESTTOOLVMOPTS} -d ${SPIDIR}${FS}dest \
     ${SPIDIR}${FS}src${FS}tznp.java \
--- a/jdk/test/java/util/PluggableLocale/ExecTest.sh	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/util/PluggableLocale/ExecTest.sh	Wed Jul 05 22:05:22 2017 +0200
@@ -93,8 +93,8 @@
 esac
 
 
-EXTRA_OPTS="-XaddExports:java.base/sun.util.locale.provider=ALL-UNNAMED \
- -XaddExports:java.base/sun.util.resources=ALL-UNNAMED"
+EXTRA_OPTS="--add-exports java.base/sun.util.locale.provider=ALL-UNNAMED \
+ --add-exports java.base/sun.util.resources=ALL-UNNAMED"
 
 # compile
 cp ${TESTSRC}${FS}ProviderTest.java .
--- a/jdk/test/java/util/ResourceBundle/Bug6299235Test.sh	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/util/ResourceBundle/Bug6299235Test.sh	Wed Jul 05 22:05:22 2017 +0200
@@ -68,7 +68,7 @@
 ${TESTJAVA}/bin/jar xf ${TESTSRC}/awtres.jar
 
 echo 
-${TESTJAVA}/bin/java ${TESTVMOPTS} -Xpatch:java.desktop=${PATCHDIR}/java.desktop \
+${TESTJAVA}/bin/java ${TESTVMOPTS} --patch-module java.desktop=${PATCHDIR}/java.desktop \
      -cp ${TESTCLASSES} Bug6299235Test
 
 if [ $? -ne 0 ]
--- a/jdk/test/java/util/ResourceBundle/modules/appbasic/appbasic.sh	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/util/ResourceBundle/modules/appbasic/appbasic.sh	Wed Jul 05 22:05:22 2017 +0200
@@ -47,7 +47,7 @@
   mkdir -p mods/$B
   CLASSES="`find $TESTSRC/src/$B -name '*.java'`"
   if [ "x$CLASSES" != x ]; then
-    $JAVAC -g -d mods -modulesourcepath $TESTSRC/src -cp mods/test $CLASSES
+    $JAVAC -g -d mods --module-source-path $TESTSRC/src -cp mods/test $CLASSES
   fi
   PROPS="`(cd $TESTSRC/src/$B; find . -name '*.properties')`"
   if [ "x$PROPS" != x ]; then
@@ -61,8 +61,8 @@
 done
 
 mkdir -p mods/test
-$JAVAC -g -d mods -modulesourcepath $TESTSRC/src `find $TESTSRC/src/test -name "*.java"`
+$JAVAC -g -d mods --module-source-path $TESTSRC/src `find $TESTSRC/src/test -name "*.java"`
 
-$JAVA -mp mods -m test/jdk.test.Main de fr ja zh-tw en de
+$JAVA -p mods -m test/jdk.test.Main de fr ja zh-tw en de
 
 exit $?
--- a/jdk/test/java/util/ResourceBundle/modules/appbasic2/appbasic2.sh	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/util/ResourceBundle/modules/appbasic2/appbasic2.sh	Wed Jul 05 22:05:22 2017 +0200
@@ -47,7 +47,7 @@
   mkdir -p mods/$B
   CLASSES="`find $TESTSRC/src/$B -name '*.java'`"
   if [ "x$CLASSES" != x ]; then
-    $JAVAC -g -d mods -modulesourcepath $TESTSRC/src -cp mods/test $CLASSES
+    $JAVAC -g -d mods --module-source-path $TESTSRC/src -cp mods/test $CLASSES
   fi
   PROPS="`(cd $TESTSRC/src/$B; find . -name '*.properties')`"
   if [ "x$PROPS" != x ]; then
@@ -61,8 +61,8 @@
 done
 
 mkdir -p mods/test
-$JAVAC -g -d mods -modulesourcepath $TESTSRC/src `find $TESTSRC/src/test -name "*.java"`
+$JAVAC -g -d mods --module-source-path $TESTSRC/src `find $TESTSRC/src/test -name "*.java"`
 
-$JAVA -mp mods -m test/jdk.test.Main de fr ja zh-tw en de
+$JAVA -p mods -m test/jdk.test.Main de fr ja zh-tw en de
 
 exit $?
--- a/jdk/test/java/util/ResourceBundle/modules/basic/basic.sh	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/util/ResourceBundle/modules/basic/basic.sh	Wed Jul 05 22:05:22 2017 +0200
@@ -52,7 +52,7 @@
   mkdir -p mods/$B
   CLASSES="`find $TESTSRC/src/$B -name '*.java'`"
   if [ "x$CLASSES" != x ]; then
-    $JAVAC -g -d mods -modulesourcepath $TESTSRC/src $CP $CLASSES
+    $JAVAC -g -d mods --module-source-path $TESTSRC/src $CP $CLASSES
   fi
   PROPS="`(cd $TESTSRC/src/$B; find . -name '*.properties')`"
   if [ "x$PROPS" != x ]; then
@@ -67,7 +67,7 @@
 done
 
 mkdir -p mods/test
-$JAVAC -g -cp mods/mainbundles -d mods -modulesourcepath $TESTSRC/src \
+$JAVAC -g -cp mods/mainbundles -d mods --module-source-path $TESTSRC/src \
     `find $TESTSRC/src/test -name "*.java"`
 
 # Create a jar to be added to the class path. Expected only properties files are
@@ -81,9 +81,9 @@
 STATUS=0
 
 echo "jdk.test.Main should load bundles using ResourceBundleProviders."
-$JAVA -mp mods -m test/jdk.test.Main de fr ja ja-jp zh-tw en de ja-jp || STATUS=1
+$JAVA -p mods -m test/jdk.test.Main de fr ja ja-jp zh-tw en de ja-jp || STATUS=1
 
 echo "jdk.test.Main should NOT load bundles from the jar file specified by the class-path."
-$JAVA -cp extra.jar -mp mods -m test/jdk.test.Main es vi && STATUS=1
+$JAVA -cp extra.jar -p mods -m test/jdk.test.Main es vi && STATUS=1
 
 exit $STATUS
--- a/jdk/test/java/util/ResourceBundle/modules/modlocal/modlocal.sh	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/util/ResourceBundle/modules/modlocal/modlocal.sh	Wed Jul 05 22:05:22 2017 +0200
@@ -57,7 +57,7 @@
     done
 fi
 
-$JAVAC -g -d mods -modulesourcepath $TESTSRC/src \
+$JAVAC -g -d mods --module-source-path $TESTSRC/src \
        -cp mods/bundles `find $TESTSRC/src/test -name "*.java"`
 
 # Create a jar to be added to the class path. Expected properties files are
@@ -69,9 +69,9 @@
 STATUS=0
 
 echo 'jdk.test.Main should load bundles local to named module "test".'
-$JAVA -mp mods -m test/jdk.test.Main de fr ja zh-tw en de || STATUS=1
+$JAVA -p mods -m test/jdk.test.Main de fr ja zh-tw en de || STATUS=1
 
 echo "jdk.test.Main should NOT load bundles from the jar file specified by the class-path."
-$JAVA -cp extra.jar -mp mods -m test/jdk.test.Main vi && STATUS=1
+$JAVA -cp extra.jar -p mods -m test/jdk.test.Main vi && STATUS=1
 
 exit $STATUS
--- a/jdk/test/java/util/ResourceBundle/modules/security/TestPermission.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/util/ResourceBundle/modules/security/TestPermission.java	Wed Jul 05 22:05:22 2017 +0200
@@ -59,7 +59,7 @@
     public void compileAll() throws Exception {
         for (String mn : modules) {
             Path msrc = SRC_DIR.resolve(mn);
-            assertTrue(CompilerUtils.compile(msrc, MODS_DIR, "-modulesourcepath", SRC_DIR.toString()));
+            assertTrue(CompilerUtils.compile(msrc, MODS_DIR, "--module-source-path", SRC_DIR.toString()));
         }
     }
 
@@ -68,7 +68,7 @@
      */
     @Test
     public void runTest() throws Exception {
-        int exitValue = executeTestJava("-mp", MODS_DIR.toString(),
+        int exitValue = executeTestJava("--module-path", MODS_DIR.toString(),
                                         "-m", "test/jdk.test.Main")
                             .outputTo(System.out)
                             .errorTo(System.out)
--- a/jdk/test/java/util/ResourceBundle/modules/simple/simple.sh	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/util/ResourceBundle/modules/simple/simple.sh	Wed Jul 05 22:05:22 2017 +0200
@@ -50,7 +50,7 @@
 mkdir -p mods/$B
 CLASSES="`find $TESTSRC/src/$B -name '*.java'`"
 if [ "x$CLASSES" != x ]; then
-    $JAVAC -g -d mods -modulesourcepath $TESTSRC/src $CLASSES
+    $JAVAC -g -d mods --module-source-path $TESTSRC/src $CLASSES
 fi
 PROPS="`(cd $TESTSRC/src/$B; find . -name '*.properties')`"
 if [ "x$PROPS" != x ]; then
@@ -62,9 +62,9 @@
     done
 fi
 
-$JAVAC -g -d mods -modulesourcepath $TESTSRC/src \
+$JAVAC -g -d mods --module-source-path $TESTSRC/src \
        -cp mods/bundles `find $TESTSRC/src/test -name "*.java"`
 
-$JAVA -mp mods -m test/jdk.test.Main de fr ja zh-tw en de
+$JAVA -p mods -m test/jdk.test.Main de fr ja zh-tw en de
 
 exit $?
--- a/jdk/test/java/util/ResourceBundle/modules/visibility/visibility.sh	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/util/ResourceBundle/modules/visibility/visibility.sh	Wed Jul 05 22:05:22 2017 +0200
@@ -57,7 +57,7 @@
     mkdir -p mods/$M
     CLASSES="`find $TESTSRC/src/$M -name '*.java'`"
     if [ "x$CLASSES" != x ]; then
-        $JAVAC -g -d mods -modulesourcepath $TESTSRC/src $CLASSES
+        $JAVAC -g -d mods --module-source-path $TESTSRC/src $CLASSES
     fi
     PROPS="`(cd $TESTSRC/src/$M; find . -name '*.properties')`"
     if [ "x$PROPS" != x ]; then
@@ -96,23 +96,23 @@
 
 # jdk.test.resources.{classes,props}.* are available only to named module "test"
 # by ResourceBundleProvider.
-runJava -mp mods -m test/jdk.test.TestWithNoModuleArg \
+runJava -p mods -m test/jdk.test.TestWithNoModuleArg \
     jdk.test.resources.classes.MyResources true
-runJava -mp mods -m test/jdk.test.TestWithNoModuleArg \
+runJava -p mods -m test/jdk.test.TestWithNoModuleArg \
     jdk.test.resources.props.MyResources true
-runJava -mp mods -m embargo/jdk.embargo.TestWithNoModuleArg \
+runJava -p mods -m embargo/jdk.embargo.TestWithNoModuleArg \
     jdk.test.resources.classes.MyResources false
-runJava -mp mods -m embargo/jdk.embargo.TestWithNoModuleArg \
+runJava -p mods -m embargo/jdk.embargo.TestWithNoModuleArg \
     jdk.test.resources.props.MyResources false
 
 # Add mods/named.bundles to the class path.
-runJava -cp mods/named.bundles -mp mods -m test/jdk.test.TestWithNoModuleArg \
+runJava -cp mods/named.bundles -p mods -m test/jdk.test.TestWithNoModuleArg \
     jdk.test.resources.classes.MyResources true
-runJava -cp mods/named.bundles -mp mods -m test/jdk.test.TestWithNoModuleArg \
+runJava -cp mods/named.bundles -p mods -m test/jdk.test.TestWithNoModuleArg \
     jdk.test.resources.props.MyResources true
-runJava -cp mods/named.bundles -mp mods -m embargo/jdk.embargo.TestWithNoModuleArg \
+runJava -cp mods/named.bundles -p mods -m embargo/jdk.embargo.TestWithNoModuleArg \
     jdk.test.resources.classes.MyResources false
-runJava -cp mods/named.bundles -mp mods -m embargo/jdk.embargo.TestWithNoModuleArg \
+runJava -cp mods/named.bundles -p mods -m embargo/jdk.embargo.TestWithNoModuleArg \
     jdk.test.resources.props.MyResources false
 
 # Tests using jdk.test.TestWithUnnamedModuleArg and jdk.embargo.TestWithUnnamedModuleArg
@@ -120,37 +120,37 @@
 
 # jdk.test.resources.classes is exported to named module "test".
 # IllegalAccessException is thrown in ResourceBundle.Control.newBundle().
-runJava -mp mods -m test/jdk.test.TestWithUnnamedModuleArg \
+runJava -p mods -m test/jdk.test.TestWithUnnamedModuleArg \
     jdk.test.resources.classes.MyResources false
 
 # jdk.test.resources.props is exported to named module "test".
 # loader.getResource() doesn't find jdk.test.resources.props.MyResources.
-runJava -mp mods -m test/jdk.test.TestWithUnnamedModuleArg \
+runJava -p mods -m test/jdk.test.TestWithUnnamedModuleArg \
     jdk.test.resources.props.MyResources false
 
 # IllegalAccessException is thrown in ResourceBundle.Control.newBundle().
-runJava -mp mods -m embargo/jdk.embargo.TestWithUnnamedModuleArg \
+runJava -p mods -m embargo/jdk.embargo.TestWithUnnamedModuleArg \
     jdk.test.resources.classes.MyResources false
 # jdk.test.resources.props is exported to named module "test".
 # loader.getResource() doesn't find jdk.test.resources.props.MyResources.
-runJava -mp mods -m embargo/jdk.embargo.TestWithUnnamedModuleArg \
+runJava -p mods -m embargo/jdk.embargo.TestWithUnnamedModuleArg \
     jdk.test.resources.props.MyResources false
 
 # Add mods/named.bundles to the class path
 
 # IllegalAccessException is thrown in ResourceBundle.Control.newBundle().
-runJava -cp mods/named.bundles -mp mods -m test/jdk.test.TestWithUnnamedModuleArg \
+runJava -cp mods/named.bundles -p mods -m test/jdk.test.TestWithUnnamedModuleArg \
         jdk.test.resources.classes.MyResources false
 # loader.getResource() finds jdk.test.resources.exported.props.MyResources.
-runJava -cp mods/named.bundles -mp mods -m test/jdk.test.TestWithUnnamedModuleArg \
+runJava -cp mods/named.bundles -p mods -m test/jdk.test.TestWithUnnamedModuleArg \
         jdk.test.resources.props.MyResources true
 
 # jdk.test.resources.exported.classes.MyResources is treated
 # as if the class is in an unnamed module.
-runJava -cp mods/named.bundles -mp mods -m embargo/jdk.embargo.TestWithUnnamedModuleArg \
+runJava -cp mods/named.bundles -p mods -m embargo/jdk.embargo.TestWithUnnamedModuleArg \
         jdk.test.resources.classes.MyResources true
 # loader.getResource() finds jdk.test.resources.exported.props.MyResources.
-runJava -cp mods/named.bundles -mp mods -m embargo/jdk.embargo.TestWithUnnamedModuleArg \
+runJava -cp mods/named.bundles -p mods -m embargo/jdk.embargo.TestWithUnnamedModuleArg \
         jdk.test.resources.props.MyResources true
 
 #################################################
@@ -160,23 +160,23 @@
 # neither of which specifies an unnamed module with ResourceBundle.getBundle.
 
 # None of jdk.test.resources.exported.** is available to the named modules.
-runJava -mp mods -m test/jdk.test.TestWithNoModuleArg \
+runJava -p mods -m test/jdk.test.TestWithNoModuleArg \
     jdk.test.resources.exported.classes.MyResources false
-runJava -mp mods -m test/jdk.test.TestWithNoModuleArg \
+runJava -p mods -m test/jdk.test.TestWithNoModuleArg \
     jdk.test.resources.exported.props.MyResources false
-runJava -mp mods -m embargo/jdk.embargo.TestWithNoModuleArg \
+runJava -p mods -m embargo/jdk.embargo.TestWithNoModuleArg \
     jdk.test.resources.exported.classes.MyResources false
-runJava -mp mods -m embargo/jdk.embargo.TestWithNoModuleArg \
+runJava -p mods -m embargo/jdk.embargo.TestWithNoModuleArg \
     jdk.test.resources.exported.props.MyResources false
 
 # Add mods/exported.named.bundles to the class path.
-runJava -cp mods/exported.named.bundles -mp mods -m test/jdk.test.TestWithNoModuleArg \
+runJava -cp mods/exported.named.bundles -p mods -m test/jdk.test.TestWithNoModuleArg \
     jdk.test.resources.exported.classes.MyResources false
-runJava -cp mods/exported.named.bundles -mp mods -m test/jdk.test.TestWithNoModuleArg \
+runJava -cp mods/exported.named.bundles -p mods -m test/jdk.test.TestWithNoModuleArg \
     jdk.test.resources.exported.props.MyResources false
-runJava -cp mods/exported.named.bundles -mp mods -m embargo/jdk.embargo.TestWithNoModuleArg \
+runJava -cp mods/exported.named.bundles -p mods -m embargo/jdk.embargo.TestWithNoModuleArg \
     jdk.test.resources.exported.classes.MyResources false
-runJava -cp mods/exported.named.bundles -mp mods -m embargo/jdk.embargo.TestWithNoModuleArg \
+runJava -cp mods/exported.named.bundles -p mods -m embargo/jdk.embargo.TestWithNoModuleArg \
     jdk.test.resources.exported.props.MyResources false
 
 # Tests using jdk.test.TestWithUnnamedModuleArg and jdk.embargo.TestWithUnnamedModuleArg
@@ -184,36 +184,36 @@
 
 # loader.loadClass() doesn't find jdk.test.resources.exported.classes.MyResources
 # and throws a ClassNotFoundException.
-runJava -mp mods -m test/jdk.test.TestWithUnnamedModuleArg \
+runJava -p mods -m test/jdk.test.TestWithUnnamedModuleArg \
         jdk.test.resources.exported.classes.MyResources false
 # The properties files in jdk.test.resources.exported.props are not found with loader.getResource().
-runJava -mp mods -m test/jdk.test.TestWithUnnamedModuleArg \
+runJava -p mods -m test/jdk.test.TestWithUnnamedModuleArg \
         jdk.test.resources.exported.props.MyResources false
 
 
 # loader.loadClass() doesn't find jdk.test.resources.exported.classes.MyResources
 # and throws a ClassNotFoundException.
-runJava -mp mods -m embargo/jdk.embargo.TestWithUnnamedModuleArg \
+runJava -p mods -m embargo/jdk.embargo.TestWithUnnamedModuleArg \
         jdk.test.resources.exported.classes.MyResources false
 # The properties files in jdk.test.resources.exported.props are not found
 # with loader.getResource().
-runJava -mp mods -m embargo/jdk.embargo.TestWithUnnamedModuleArg \
+runJava -p mods -m embargo/jdk.embargo.TestWithUnnamedModuleArg \
         jdk.test.resources.exported.props.MyResources false
 
 # Add mods/exported.named.bundles to the class path.
 
 # jdk.test.resources.exported.classes.MyResources.getModule().isNamed() returns false.
-runJava -cp mods/exported.named.bundles -mp mods -m test/jdk.test.TestWithUnnamedModuleArg \
+runJava -cp mods/exported.named.bundles -p mods -m test/jdk.test.TestWithUnnamedModuleArg \
         jdk.test.resources.exported.classes.MyResources true
 # loader.getResource() finds jdk.test.resources.exported.props.MyResources.
-runJava -cp mods/exported.named.bundles -mp mods -m test/jdk.test.TestWithUnnamedModuleArg \
+runJava -cp mods/exported.named.bundles -p mods -m test/jdk.test.TestWithUnnamedModuleArg \
         jdk.test.resources.exported.props.MyResources true
 
 # jdk.test.resources.exported.classes.MyResources.getModule().isNamed() returns false.
-runJava -cp mods/exported.named.bundles -mp mods -m embargo/jdk.embargo.TestWithUnnamedModuleArg \
+runJava -cp mods/exported.named.bundles -p mods -m embargo/jdk.embargo.TestWithUnnamedModuleArg \
         jdk.test.resources.exported.classes.MyResources true
 # loader.getResource() finds jdk.test.resources.exported.props.MyResources.
-runJava -cp mods/exported.named.bundles -mp mods -m embargo/jdk.embargo.TestWithUnnamedModuleArg \
+runJava -cp mods/exported.named.bundles -p mods -m embargo/jdk.embargo.TestWithUnnamedModuleArg \
         jdk.test.resources.exported.props.MyResources true
 
 #######################################
--- a/jdk/test/java/util/ResourceBundle/modules/xmlformat/xmlformat.sh	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/util/ResourceBundle/modules/xmlformat/xmlformat.sh	Wed Jul 05 22:05:22 2017 +0200
@@ -48,7 +48,7 @@
 mkdir -p mods/$B
 CLASSES="`find $TESTSRC/src/$B -name '*.java'`"
 if [ "x$CLASSES" != x ]; then
-    $JAVAC -g -d mods -modulesourcepath $TESTSRC/src $CLASSES
+    $JAVAC -g -d mods --module-source-path $TESTSRC/src $CLASSES
 fi
 PROPS="`(cd $TESTSRC/src/$B; find . -name '*.xml')`"
 if [ "x$PROPS" != x ]; then
@@ -60,9 +60,9 @@
     done
 fi
 
-$JAVAC -g -d mods -modulesourcepath $TESTSRC/src \
+$JAVAC -g -d mods --module-source-path $TESTSRC/src \
        -cp mods/bundles `find $TESTSRC/src/test -name "*.java"`
 
-$JAVA -mp mods -m test/jdk.test.Main de fr ja zh-tw en de
+$JAVA -p mods -m test/jdk.test.Main de fr ja zh-tw en de
 
 exit $?
--- a/jdk/test/java/util/ServiceLoader/modules/ServicesTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/util/ServiceLoader/modules/ServicesTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -105,13 +105,13 @@
 
 
     /**
-     * Run test with -modulepath.
+     * Run test with --module-path.
      *
      * BananaScriptEngine should be found.
      */
     public void runWithModulePath() throws Exception {
         int exitValue
-            = executeTestJava("-mp", MODS_DIR.toString(),
+            = executeTestJava("--module-path", MODS_DIR.toString(),
                               "-m", "test/test.Main",
                               "BananaScriptEngine")
                 .outputTo(System.out)
@@ -123,13 +123,13 @@
 
 
     /**
-     * Run test with -modulepath and -classpath.
+     * Run test with --module-path and -classpath.
      *
      * Both BananaScriptEngine and PearScriptEngine should be found
      */
     public void runWithModulePathAndClassPath() throws Exception {
         int exitValue
-            = executeTestJava("-mp", MODS_DIR.toString(),
+            = executeTestJava("--module-path", MODS_DIR.toString(),
                               "-cp", CLASSES_DIR.toString(),
                               "-m", "test/test.Main",
                               "BananaScriptEngine", "PearScriptEngine")
--- a/jdk/test/java/util/concurrent/BlockingQueue/PollMemoryLeak.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/util/concurrent/BlockingQueue/PollMemoryLeak.java	Wed Jul 05 22:05:22 2017 +0200
@@ -26,43 +26,133 @@
  * However, the following notice accompanied the original version of this
  * file:
  *
- * Written by Doug Lea with assistance from members of JCP JSR-166
- * Expert Group and released to the public domain, as explained at
+ * Written by Doug Lea and Martin Buchholz with assistance from
+ * members of JCP JSR-166 Expert Group and released to the public
+ * domain, as explained at
  * http://creativecommons.org/publicdomain/zero/1.0/
  */
 
 /*
  * @test
  * @bug 6236036 6264015
- * @compile PollMemoryLeak.java
- * @run main/othervm -Xmx8m PollMemoryLeak
- * @summary  Checks for OutOfMemoryError when an unbounded
- * number of aborted timed waits occur without a signal.
+ * @summary Checks for a memory leak when a sequence of aborted timed
+ * waits occur without a signal.  Uses the strategy of detecting
+ * changes in the size of the object graph retained by a root object.
  */
 
+import java.lang.reflect.AccessibleObject;
+import java.lang.reflect.Array;
+import java.lang.reflect.Field;
+import java.lang.reflect.Modifier;
+import java.util.ArrayDeque;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.IdentityHashMap;
+import java.util.Set;
 import java.util.concurrent.ArrayBlockingQueue;
 import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.LinkedBlockingDeque;
 import java.util.concurrent.LinkedBlockingQueue;
 import java.util.concurrent.LinkedTransferQueue;
+import java.util.concurrent.PriorityBlockingQueue;
 import java.util.concurrent.SynchronousQueue;
 import java.util.concurrent.TimeUnit;
 
 public class PollMemoryLeak {
-    public static void main(String[] args) throws InterruptedException {
-        final BlockingQueue[] qs = {
-            new LinkedBlockingDeque(10),
-            new LinkedBlockingQueue(10),
-            new LinkedTransferQueue(),
-            new ArrayBlockingQueue(10),
-            new ArrayBlockingQueue(10, true),
-            new SynchronousQueue(),
-            new SynchronousQueue(true),
-        };
-        final long start = System.currentTimeMillis();
-        final long end = start + 10 * 1000;
-        while (System.currentTimeMillis() < end)
-            for (BlockingQueue q : qs)
-                q.poll(1, TimeUnit.NANOSECONDS);
+    public static void main(String[] args) throws Throwable {
+        new PollMemoryLeak().main();
+    }
+
+    void main() throws Throwable {
+        test(new LinkedBlockingDeque(10));
+        test(new LinkedBlockingQueue(10));
+        test(new LinkedTransferQueue());
+        test(new ArrayBlockingQueue(10));
+        test(new PriorityBlockingQueue());
+        test(new SynchronousQueue());
+        test(new SynchronousQueue(true));
+    }
+
+    void test(BlockingQueue q) throws Throwable {
+        assertNoLeak(q, () -> timedPoll(q));
+
+        // A demo that the leak detection infrastructure works
+        // assertNoLeak(q, () -> q.add(1));
+        // printRetainedObjects(q);
+    }
+
+    static void timedPoll(BlockingQueue q) {
+        try { q.poll(1, TimeUnit.NANOSECONDS); }
+        catch (InterruptedException ex) { throw new AssertionError(ex); }
+    }
+
+    // -------- leak detection infrastructure ---------------
+    void assertNoLeak(Object root, Runnable r) {
+        int prev = retainedObjects(root).size();
+        for (int i = 0; i < 3; i++) {
+            for (int j = 0; j < 3; j++) r.run();
+            int next = retainedObjects(root).size();
+            if (next <= prev)
+                return;
+            prev = next;
+        }
+        throw new AssertionError(
+            String.format("probable memory leak in %s: %s",
+                          root.getClass().getSimpleName(), root));
+    }
+
+    ConcurrentHashMap<Class<?>, Collection<Field>> classFields
+        = new ConcurrentHashMap<Class<?>, Collection<Field>>();
+
+    Collection<Field> referenceFieldsOf(Class<?> k) {
+        Collection<Field> fields = classFields.get(k);
+        if (fields == null) {
+            fields = new ArrayDeque<Field>();
+            ArrayDeque<Field> allFields = new ArrayDeque<Field>();
+            for (Class<?> c = k; c != null; c = c.getSuperclass())
+                for (Field field : c.getDeclaredFields())
+                    if (!Modifier.isStatic(field.getModifiers())
+                        && !field.getType().isPrimitive())
+                        fields.add(field);
+            AccessibleObject.setAccessible(
+                fields.toArray(new AccessibleObject[0]), true);
+            classFields.put(k, fields);
+        }
+        return fields;
+    }
+
+    static Object get(Field field, Object x) {
+        try { return field.get(x); }
+        catch (IllegalAccessException ex) { throw new AssertionError(ex); }
+    }
+
+    Set<Object> retainedObjects(Object x) {
+        ArrayDeque<Object> todo = new ArrayDeque<Object>() {
+            public void push(Object x) { if (x != null) super.push(x); }};
+        Set<Object> uniqueObjects = Collections.newSetFromMap(
+            new IdentityHashMap<Object, Boolean>());
+        todo.push(x);
+        while (!todo.isEmpty()) {
+            Object y = todo.pop();
+            if (uniqueObjects.contains(y))
+                continue;
+            uniqueObjects.add(y);
+            Class<?> k = y.getClass();
+            if (k.isArray() && !k.getComponentType().isPrimitive()) {
+                for (int i = 0, len = Array.getLength(y); i < len; i++)
+                    todo.push(Array.get(y, i));
+            } else {
+                for (Field field : referenceFieldsOf(k))
+                    todo.push(get(field, y));
+            }
+        }
+        return uniqueObjects;
+    }
+
+    /** for debugging the retained object graph */
+    void printRetainedObjects(Object x) {
+        for (Object y : retainedObjects(x))
+            System.out.printf("%s : %s%n", y.getClass().getSimpleName(), y);
     }
 }
--- a/jdk/test/java/util/concurrent/ConcurrentLinkedQueue/RemoveLeak.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/util/concurrent/ConcurrentLinkedQueue/RemoveLeak.java	Wed Jul 05 22:05:22 2017 +0200
@@ -35,26 +35,120 @@
  * @test
  * @bug 8054446 8137184 8137185
  * @summary Regression test for memory leak in remove(Object)
- * @run main/othervm -Xmx2200k RemoveLeak
  */
 
+import java.lang.reflect.AccessibleObject;
+import java.lang.reflect.Array;
+import java.lang.reflect.Field;
+import java.lang.reflect.Modifier;
+import java.util.ArrayDeque;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.IdentityHashMap;
+import java.util.Set;
+import java.util.concurrent.ArrayBlockingQueue;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentLinkedDeque;
 import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.LinkedBlockingDeque;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.LinkedTransferQueue;
+import java.util.concurrent.PriorityBlockingQueue;
 
 public class RemoveLeak {
-    public static void main(String[] args) {
-        int i = 0;
-        // Without bug fix, OutOfMemoryError was observed at iteration 65120
-        int iterations = 10 * 65120;
-        try {
-            ConcurrentLinkedQueue<Long> queue = new ConcurrentLinkedQueue<>();
-            queue.add(0L);
-            while (i++ < iterations) {
-                queue.add(1L);
-                queue.remove(1L);
+    public static void main(String[] args) throws Throwable {
+        new RemoveLeak().main();
+    }
+
+    void main() throws Throwable {
+        test(new ConcurrentLinkedDeque());
+        test(new ConcurrentLinkedQueue());
+        test(new LinkedBlockingDeque(10));
+        test(new LinkedBlockingQueue(10));
+        test(new LinkedTransferQueue());
+        test(new ArrayBlockingQueue(10));
+        test(new PriorityBlockingQueue());
+    }
+
+    void test(Collection c) throws Throwable {
+        assertNoLeak(c, () -> addRemove(c));
+
+        // A demo that the leak detection infrastructure works
+        // assertNoLeak(c, () -> c.add(1));
+        // printRetainedObjects(c);
+    }
+
+    static void addRemove(Collection c) {
+        c.add(1);
+        c.remove(1);
+    }
+
+    // -------- leak detection infrastructure ---------------
+    void assertNoLeak(Object root, Runnable r) {
+        int prev = retainedObjects(root).size();
+        for (int i = 0; i < 3; i++) {
+            for (int j = 0; j < 3; j++) r.run();
+            int next = retainedObjects(root).size();
+            if (next <= prev)
+                return;
+            prev = next;
+        }
+        throw new AssertionError(
+            String.format("probable memory leak in %s: %s",
+                          root.getClass().getSimpleName(), root));
+    }
+
+    ConcurrentHashMap<Class<?>, Collection<Field>> classFields
+        = new ConcurrentHashMap<Class<?>, Collection<Field>>();
+
+    Collection<Field> referenceFieldsOf(Class<?> k) {
+        Collection<Field> fields = classFields.get(k);
+        if (fields == null) {
+            fields = new ArrayDeque<Field>();
+            ArrayDeque<Field> allFields = new ArrayDeque<Field>();
+            for (Class<?> c = k; c != null; c = c.getSuperclass())
+                for (Field field : c.getDeclaredFields())
+                    if (!Modifier.isStatic(field.getModifiers())
+                        && !field.getType().isPrimitive())
+                        fields.add(field);
+            AccessibleObject.setAccessible(
+                fields.toArray(new AccessibleObject[0]), true);
+            classFields.put(k, fields);
+        }
+        return fields;
+    }
+
+    static Object get(Field field, Object x) {
+        try { return field.get(x); }
+        catch (IllegalAccessException ex) { throw new AssertionError(ex); }
+    }
+
+    Set<Object> retainedObjects(Object x) {
+        ArrayDeque<Object> todo = new ArrayDeque<Object>() {
+            public void push(Object x) { if (x != null) super.push(x); }};
+        Set<Object> uniqueObjects = Collections.newSetFromMap(
+            new IdentityHashMap<Object, Boolean>());
+        todo.push(x);
+        while (!todo.isEmpty()) {
+            Object y = todo.pop();
+            if (uniqueObjects.contains(y))
+                continue;
+            uniqueObjects.add(y);
+            Class<?> k = y.getClass();
+            if (k.isArray() && !k.getComponentType().isPrimitive()) {
+                for (int i = 0, len = Array.getLength(y); i < len; i++)
+                    todo.push(Array.get(y, i));
+            } else {
+                for (Field field : referenceFieldsOf(k))
+                    todo.push(get(field, y));
             }
-        } catch (Error t) {
-            System.err.printf("failed at iteration %d/%d%n", i, iterations);
-            throw t;
         }
+        return uniqueObjects;
+    }
+
+    /** for debugging the retained object graph */
+    void printRetainedObjects(Object x) {
+        for (Object y : retainedObjects(x))
+            System.out.printf("%s : %s%n", y.getClass().getSimpleName(), y);
     }
 }
--- a/jdk/test/java/util/concurrent/forkjoin/FJExceptionTableLeak.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/util/concurrent/forkjoin/FJExceptionTableLeak.java	Wed Jul 05 22:05:22 2017 +0200
@@ -26,51 +26,117 @@
  * However, the following notice accompanied the original version of this
  * file:
  *
- * Written by Doug Lea with assistance from members of JCP JSR-166
- * Expert Group and released to the public domain, as explained at
+ * Written by Doug Lea and Martin Buchholz with assistance from
+ * members of JCP JSR-166 Expert Group and released to the public
+ * domain, as explained at
  * http://creativecommons.org/publicdomain/zero/1.0/
  */
 
 /*
  * @test
- * @author Doug Lea
  * @bug 8004138
- * @key intermittent
- * @summary Check if ForkJoinPool table leaks thrown exceptions.
- * @run main/othervm -Xmx8m -Djava.util.concurrent.ForkJoinPool.common.parallelism=4 FJExceptionTableLeak
+ * @summary Checks that ForkJoinTask thrown exceptions are not leaked.
+ * This whitebox test is sensitive to forkjoin implementation details.
  */
 
+import static java.util.concurrent.TimeUnit.SECONDS;
+
+import java.lang.ref.WeakReference;
+import java.lang.reflect.Field;
+import java.util.ArrayList;
+import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.ForkJoinPool;
+import java.util.concurrent.ForkJoinTask;
 import java.util.concurrent.RecursiveAction;
+import java.util.function.BooleanSupplier;
 
 public class FJExceptionTableLeak {
-    // This test was observed to fail with pre-bug-fix jdk7 -Xmx8m,
-    // using STEPS = 220 and TASKS_PER_STEP = 100
-    static final int PRE_BUG_FIX_FAILURE_STEPS = 220;
-    static final int STEPS = 10 * PRE_BUG_FIX_FAILURE_STEPS;
-    static final int TASKS_PER_STEP = 100;
-
     static class FailingTaskException extends RuntimeException {}
     static class FailingTask extends RecursiveAction {
-        public void compute() {
-            throw new FailingTaskException();
-        }
+        public void compute() { throw new FailingTaskException(); }
+    }
+
+    static int bucketsInuse(Object[] exceptionTable) {
+        int count = 0;
+        for (Object x : exceptionTable)
+            if (x != null) count++;
+        return count;
     }
 
-    public static void main(String[] args) throws InterruptedException {
-        ForkJoinPool pool = new ForkJoinPool(4);
-        FailingTask[] tasks = new FailingTask[TASKS_PER_STEP];
-        for (int k = 0; k < STEPS; ++k) {
-            for (int i = 0; i < tasks.length; ++i)
-                tasks[i] = new FailingTask();
-            for (int i = 0; i < tasks.length; ++i)
-                pool.execute(tasks[i]);
-            for (int i = 0; i < tasks.length; ++i) {
+    public static void main(String[] args) throws Exception {
+        final ForkJoinPool pool = new ForkJoinPool(4);
+        final Field exceptionTableField =
+            ForkJoinTask.class.getDeclaredField("exceptionTable");
+        exceptionTableField.setAccessible(true);
+        final Object[] exceptionTable = (Object[]) exceptionTableField.get(null);
+
+        if (bucketsInuse(exceptionTable) != 0) throw new AssertionError();
+
+        final ArrayList<FailingTask> tasks = new ArrayList<>();
+
+        // Keep submitting failing tasks until most of the exception
+        // table buckets are in use
+        do {
+            for (int i = 0; i < exceptionTable.length; i++) {
+                FailingTask task = new FailingTask();
+                pool.execute(task);
+                tasks.add(task); // retain strong refs to all tasks, for now
+            }
+            for (FailingTask task : tasks) {
                 try {
-                    tasks[i].join();
+                    task.join();
                     throw new AssertionError("should throw");
                 } catch (FailingTaskException success) {}
             }
+        } while (bucketsInuse(exceptionTable) < exceptionTable.length * 3 / 4);
+
+        // Retain a strong ref to one last failing task;
+        // task.join() will trigger exception table expunging.
+        FailingTask lastTask = tasks.get(0);
+
+        // Clear all other strong refs, making exception table cleanable
+        tasks.clear();
+
+        BooleanSupplier exceptionTableIsClean = () -> {
+            try {
+                lastTask.join();
+                throw new AssertionError("should throw");
+            } catch (FailingTaskException expected) {}
+            int count = bucketsInuse(exceptionTable);
+            if (count == 0)
+                throw new AssertionError("expected to find last task");
+            return count == 1;
+        };
+        gcAwait(exceptionTableIsClean);
+    }
+
+    // --------------- GC finalization infrastructure ---------------
+
+    /** No guarantees, but effective in practice. */
+    static void forceFullGc() {
+        CountDownLatch finalizeDone = new CountDownLatch(1);
+        WeakReference<?> ref = new WeakReference<Object>(new Object() {
+            protected void finalize() { finalizeDone.countDown(); }});
+        try {
+            for (int i = 0; i < 10; i++) {
+                System.gc();
+                if (finalizeDone.await(1L, SECONDS) && ref.get() == null) {
+                    System.runFinalization(); // try to pick up stragglers
+                    return;
+                }
+            }
+        } catch (InterruptedException unexpected) {
+            throw new AssertionError("unexpected InterruptedException");
         }
+        throw new AssertionError("failed to do a \"full\" gc");
+    }
+
+    static void gcAwait(BooleanSupplier s) {
+        for (int i = 0; i < 10; i++) {
+            if (s.getAsBoolean())
+                return;
+            forceFullGc();
+        }
+        throw new AssertionError("failed to satisfy condition");
     }
 }
--- a/jdk/test/java/util/concurrent/tck/ArrayBlockingQueueTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/util/concurrent/tck/ArrayBlockingQueueTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -492,7 +492,7 @@
             }});
 
         await(aboutToWait);
-        waitForThreadToEnterWaitState(t, LONG_DELAY_MS);
+        waitForThreadToEnterWaitState(t);
         t.interrupt();
         awaitTermination(t);
         checkEmpty(q);
--- a/jdk/test/java/util/concurrent/tck/AtomicBooleanTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/util/concurrent/tck/AtomicBooleanTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -136,11 +136,14 @@
      * getAndSet returns previous value and sets to given value
      */
     public void testGetAndSet() {
-        AtomicBoolean ai = new AtomicBoolean(true);
-        assertEquals(true, ai.getAndSet(false));
-        assertEquals(false, ai.getAndSet(false));
-        assertEquals(false, ai.getAndSet(true));
-        assertTrue(ai.get());
+        AtomicBoolean ai = new AtomicBoolean();
+        boolean[] booleans = { false, true };
+        for (boolean before : booleans)
+            for (boolean after : booleans) {
+                ai.set(before);
+                assertEquals(before, ai.getAndSet(after));
+                assertEquals(after, ai.get());
+            }
     }
 
     /**
--- a/jdk/test/java/util/concurrent/tck/ConcurrentHashMap8Test.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/util/concurrent/tck/ConcurrentHashMap8Test.java	Wed Jul 05 22:05:22 2017 +0200
@@ -433,7 +433,7 @@
         Integer[] elements = new Integer[size];
         for (int i = 0; i < size; i++)
             elements[i] = i;
-        Collections.shuffle(Arrays.asList(elements));
+        shuffle(elements);
         Collection<Integer> full = populatedSet(elements);
 
         Iterator it = full.iterator();
@@ -523,7 +523,7 @@
         Integer[] elements = new Integer[size];
         for (int i = 0; i < size; i++)
             elements[i] = i;
-        Collections.shuffle(Arrays.asList(elements));
+        shuffle(elements);
         Collection<Integer> full = populatedSet(elements);
 
         assertTrue(Arrays.asList(elements).containsAll(Arrays.asList(full.toArray())));
@@ -553,7 +553,7 @@
         Integer[] elements = new Integer[size];
         for (int i = 0; i < size; i++)
             elements[i] = i;
-        Collections.shuffle(Arrays.asList(elements));
+        shuffle(elements);
         Collection<Integer> full = populatedSet(elements);
 
         Arrays.fill(a, 42);
--- a/jdk/test/java/util/concurrent/tck/CopyOnWriteArrayListTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/util/concurrent/tck/CopyOnWriteArrayListTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -291,7 +291,7 @@
         Integer[] elements = new Integer[SIZE];
         for (int i = 0; i < SIZE; i++)
             elements[i] = i;
-        Collections.shuffle(Arrays.asList(elements));
+        shuffle(elements);
         Collection<Integer> full = populatedArray(elements);
 
         Iterator it = full.iterator();
@@ -459,7 +459,7 @@
         Integer[] elements = new Integer[SIZE];
         for (int i = 0; i < SIZE; i++)
             elements[i] = i;
-        Collections.shuffle(Arrays.asList(elements));
+        shuffle(elements);
         Collection<Integer> full = populatedArray(elements);
 
         assertTrue(Arrays.equals(elements, full.toArray()));
@@ -487,7 +487,7 @@
         Integer[] elements = new Integer[SIZE];
         for (int i = 0; i < SIZE; i++)
             elements[i] = i;
-        Collections.shuffle(Arrays.asList(elements));
+        shuffle(elements);
         Collection<Integer> full = populatedArray(elements);
 
         Arrays.fill(a, 42);
--- a/jdk/test/java/util/concurrent/tck/CopyOnWriteArraySetTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/util/concurrent/tck/CopyOnWriteArraySetTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -251,7 +251,7 @@
         Integer[] elements = new Integer[SIZE];
         for (int i = 0; i < SIZE; i++)
             elements[i] = i;
-        Collections.shuffle(Arrays.asList(elements));
+        shuffle(elements);
         Collection<Integer> full = populatedSet(elements);
 
         Iterator it = full.iterator();
@@ -338,7 +338,7 @@
         Integer[] elements = new Integer[SIZE];
         for (int i = 0; i < SIZE; i++)
             elements[i] = i;
-        Collections.shuffle(Arrays.asList(elements));
+        shuffle(elements);
         Collection<Integer> full = populatedSet(elements);
 
         assertTrue(Arrays.equals(elements, full.toArray()));
@@ -366,7 +366,7 @@
         Integer[] elements = new Integer[SIZE];
         for (int i = 0; i < SIZE; i++)
             elements[i] = i;
-        Collections.shuffle(Arrays.asList(elements));
+        shuffle(elements);
         Collection<Integer> full = populatedSet(elements);
 
         Arrays.fill(a, 42);
--- a/jdk/test/java/util/concurrent/tck/ForkJoinTask8Test.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/util/concurrent/tck/ForkJoinTask8Test.java	Wed Jul 05 22:05:22 2017 +0200
@@ -948,7 +948,7 @@
                 AsyncFib f = new AsyncFib(8);
                 FailingAsyncFib g = new FailingAsyncFib(9);
                 ForkJoinTask[] tasks = { f, g };
-                Collections.shuffle(Arrays.asList(tasks));
+                shuffle(tasks);
                 try {
                     invokeAll(tasks[0], tasks[1]);
                     shouldThrow();
@@ -975,7 +975,7 @@
                 FailingAsyncFib g = new FailingAsyncFib(9);
                 AsyncFib h = new AsyncFib(7);
                 ForkJoinTask[] tasks = { f, g, h };
-                Collections.shuffle(Arrays.asList(tasks));
+                shuffle(tasks);
                 try {
                     invokeAll(tasks[0], tasks[1], tasks[2]);
                     shouldThrow();
@@ -1002,7 +1002,7 @@
                 AsyncFib g = new AsyncFib(9);
                 AsyncFib h = new AsyncFib(7);
                 ForkJoinTask[] tasks = { f, g, h };
-                Collections.shuffle(Arrays.asList(tasks));
+                shuffle(tasks);
                 try {
                     invokeAll(Arrays.asList(tasks));
                     shouldThrow();
--- a/jdk/test/java/util/concurrent/tck/ForkJoinTaskTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/util/concurrent/tck/ForkJoinTaskTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -924,7 +924,7 @@
                 AsyncFib f = new AsyncFib(8);
                 FailingAsyncFib g = new FailingAsyncFib(9);
                 ForkJoinTask[] tasks = { f, g };
-                Collections.shuffle(Arrays.asList(tasks));
+                shuffle(tasks);
                 try {
                     invokeAll(tasks);
                     shouldThrow();
@@ -962,7 +962,7 @@
                 FailingAsyncFib g = new FailingAsyncFib(9);
                 AsyncFib h = new AsyncFib(7);
                 ForkJoinTask[] tasks = { f, g, h };
-                Collections.shuffle(Arrays.asList(tasks));
+                shuffle(tasks);
                 try {
                     invokeAll(tasks);
                     shouldThrow();
@@ -983,10 +983,9 @@
                 AsyncFib g = new AsyncFib(9);
                 AsyncFib h = new AsyncFib(7);
                 ForkJoinTask[] tasks = { f, g, h };
-                List taskList = Arrays.asList(tasks);
-                Collections.shuffle(taskList);
+                shuffle(tasks);
                 try {
-                    invokeAll(taskList);
+                    invokeAll(Arrays.asList(tasks));
                     shouldThrow();
                 } catch (FJException success) {
                     checkCompletedAbnormally(f, success);
@@ -1594,7 +1593,7 @@
                 AsyncFib f = new AsyncFib(8);
                 FailingAsyncFib g = new FailingAsyncFib(9);
                 ForkJoinTask[] tasks = { f, g };
-                Collections.shuffle(Arrays.asList(tasks));
+                shuffle(tasks);
                 try {
                     invokeAll(tasks);
                     shouldThrow();
@@ -1632,7 +1631,7 @@
                 FailingAsyncFib g = new FailingAsyncFib(9);
                 AsyncFib h = new AsyncFib(7);
                 ForkJoinTask[] tasks = { f, g, h };
-                Collections.shuffle(Arrays.asList(tasks));
+                shuffle(tasks);
                 try {
                     invokeAll(tasks);
                     shouldThrow();
@@ -1653,10 +1652,9 @@
                 AsyncFib g = new AsyncFib(9);
                 AsyncFib h = new AsyncFib(7);
                 ForkJoinTask[] tasks = { f, g, h };
-                List taskList = Arrays.asList(tasks);
-                Collections.shuffle(taskList);
+                shuffle(tasks);
                 try {
-                    invokeAll(taskList);
+                    invokeAll(Arrays.asList(tasks));
                     shouldThrow();
                 } catch (FJException success) {
                     checkCompletedAbnormally(f, success);
--- a/jdk/test/java/util/concurrent/tck/JSR166TestCase.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/util/concurrent/tck/JSR166TestCase.java	Wed Jul 05 22:05:22 2017 +0200
@@ -68,6 +68,7 @@
 import java.security.SecurityPermission;
 import java.util.ArrayList;
 import java.util.Arrays;
+import java.util.Collections;
 import java.util.Date;
 import java.util.Enumeration;
 import java.util.Iterator;
@@ -89,6 +90,7 @@
 import java.util.concurrent.Semaphore;
 import java.util.concurrent.SynchronousQueue;
 import java.util.concurrent.ThreadFactory;
+import java.util.concurrent.ThreadLocalRandom;
 import java.util.concurrent.ThreadPoolExecutor;
 import java.util.concurrent.TimeoutException;
 import java.util.concurrent.atomic.AtomicBoolean;
@@ -1278,7 +1280,7 @@
      * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
      */
     void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
-        long startTime = System.nanoTime();
+        long startTime = 0L;
         for (;;) {
             Thread.State s = thread.getState();
             if (s == Thread.State.BLOCKED ||
@@ -1287,6 +1289,8 @@
                 return;
             else if (s == Thread.State.TERMINATED)
                 fail("Unexpected thread termination");
+            else if (startTime == 0L)
+                startTime = System.nanoTime();
             else if (millisElapsedSince(startTime) > timeoutMillis) {
                 threadAssertTrue(thread.isAlive());
                 return;
@@ -1900,4 +1904,7 @@
                                1000L, MILLISECONDS,
                                new SynchronousQueue<Runnable>());
 
+    static <T> void shuffle(T[] array) {
+        Collections.shuffle(Arrays.asList(array), ThreadLocalRandom.current());
+    }
 }
--- a/jdk/test/java/util/concurrent/tck/LinkedBlockingDequeTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/util/concurrent/tck/LinkedBlockingDequeTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -792,7 +792,7 @@
             }});
 
         aboutToWait.await();
-        waitForThreadToEnterWaitState(t, LONG_DELAY_MS);
+        waitForThreadToEnterWaitState(t);
         t.interrupt();
         awaitTermination(t);
         checkEmpty(q);
--- a/jdk/test/java/util/concurrent/tck/LinkedBlockingQueueTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/util/concurrent/tck/LinkedBlockingQueueTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -481,7 +481,7 @@
             }});
 
         await(aboutToWait);
-        waitForThreadToEnterWaitState(t, LONG_DELAY_MS);
+        waitForThreadToEnterWaitState(t);
         t.interrupt();
         awaitTermination(t);
         checkEmpty(q);
--- a/jdk/test/java/util/concurrent/tck/PriorityBlockingQueueTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/util/concurrent/tck/PriorityBlockingQueueTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -437,7 +437,7 @@
             }});
 
         aboutToWait.await();
-        waitForThreadToEnterWaitState(t, LONG_DELAY_MS);
+        waitForThreadToEnterWaitState(t);
         t.interrupt();
         awaitTermination(t);
     }
--- a/jdk/test/java/util/concurrent/tck/StampedLockTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/util/concurrent/tck/StampedLockTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -34,10 +34,12 @@
 
 import static java.util.concurrent.TimeUnit.DAYS;
 import static java.util.concurrent.TimeUnit.MILLISECONDS;
+import static java.util.concurrent.TimeUnit.SECONDS;
 
 import java.util.ArrayList;
 import java.util.List;
 import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.Future;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.locks.Lock;
 import java.util.concurrent.locks.StampedLock;
@@ -57,207 +59,188 @@
     }
 
     /**
-     * A runnable calling writeLockInterruptibly
+     * Releases write lock, checking isWriteLocked before and after
      */
-    class InterruptibleLockRunnable extends CheckedRunnable {
-        final StampedLock lock;
-        InterruptibleLockRunnable(StampedLock l) { lock = l; }
-        public void realRun() throws InterruptedException {
-            lock.writeLockInterruptibly();
-        }
+    void releaseWriteLock(StampedLock lock, long stamp) {
+        assertTrue(lock.isWriteLocked());
+        assertValid(lock, stamp);
+        lock.unlockWrite(stamp);
+        assertFalse(lock.isWriteLocked());
+        assertFalse(lock.validate(stamp));
     }
 
     /**
-     * A runnable calling writeLockInterruptibly that expects to be
-     * interrupted
+     * Releases read lock, checking isReadLocked before and after
      */
-    class InterruptedLockRunnable extends CheckedInterruptedRunnable {
-        final StampedLock lock;
-        InterruptedLockRunnable(StampedLock l) { lock = l; }
-        public void realRun() throws InterruptedException {
-            lock.writeLockInterruptibly();
-        }
+    void releaseReadLock(StampedLock lock, long stamp) {
+        assertTrue(lock.isReadLocked());
+        assertValid(lock, stamp);
+        lock.unlockRead(stamp);
+        assertFalse(lock.isReadLocked());
+        assertTrue(lock.validate(stamp));
+    }
+
+    long assertNonZero(long v) {
+        assertTrue(v != 0L);
+        return v;
+    }
+
+    long assertValid(StampedLock lock, long stamp) {
+        assertTrue(stamp != 0L);
+        assertTrue(lock.validate(stamp));
+        return stamp;
+    }
+
+    void assertUnlocked(StampedLock lock) {
+        assertFalse(lock.isReadLocked());
+        assertFalse(lock.isWriteLocked());
+        assertEquals(0, lock.getReadLockCount());
+        assertValid(lock, lock.tryOptimisticRead());
+    }
+
+    List<Action> lockLockers(Lock lock) {
+        List<Action> lockers = new ArrayList<>();
+        lockers.add(() -> lock.lock());
+        lockers.add(() -> lock.lockInterruptibly());
+        lockers.add(() -> lock.tryLock());
+        lockers.add(() -> lock.tryLock(Long.MIN_VALUE, DAYS));
+        lockers.add(() -> lock.tryLock(0L, DAYS));
+        lockers.add(() -> lock.tryLock(Long.MAX_VALUE, DAYS));
+        return lockers;
     }
 
-    /**
-     * Releases write lock, checking isWriteLocked before and after
-     */
-    void releaseWriteLock(StampedLock lock, long s) {
-        assertTrue(lock.isWriteLocked());
-        lock.unlockWrite(s);
-        assertFalse(lock.isWriteLocked());
+    List<Function<StampedLock, Long>> readLockers() {
+        List<Function<StampedLock, Long>> readLockers = new ArrayList<>();
+        readLockers.add((sl) -> sl.readLock());
+        readLockers.add((sl) -> sl.tryReadLock());
+        readLockers.add((sl) -> readLockInterruptiblyUninterrupted(sl));
+        readLockers.add((sl) -> tryReadLockUninterrupted(sl, Long.MIN_VALUE, DAYS));
+        readLockers.add((sl) -> tryReadLockUninterrupted(sl, 0L, DAYS));
+        readLockers.add((sl) -> sl.tryConvertToReadLock(sl.tryOptimisticRead()));
+        return readLockers;
+    }
+
+    List<BiConsumer<StampedLock, Long>> readUnlockers() {
+        List<BiConsumer<StampedLock, Long>> readUnlockers = new ArrayList<>();
+        readUnlockers.add((sl, stamp) -> sl.unlockRead(stamp));
+        readUnlockers.add((sl, stamp) -> assertTrue(sl.tryUnlockRead()));
+        readUnlockers.add((sl, stamp) -> sl.asReadLock().unlock());
+        readUnlockers.add((sl, stamp) -> sl.unlock(stamp));
+        readUnlockers.add((sl, stamp) -> assertValid(sl, sl.tryConvertToOptimisticRead(stamp)));
+        return readUnlockers;
+    }
+
+    List<Function<StampedLock, Long>> writeLockers() {
+        List<Function<StampedLock, Long>> writeLockers = new ArrayList<>();
+        writeLockers.add((sl) -> sl.writeLock());
+        writeLockers.add((sl) -> sl.tryWriteLock());
+        writeLockers.add((sl) -> writeLockInterruptiblyUninterrupted(sl));
+        writeLockers.add((sl) -> tryWriteLockUninterrupted(sl, Long.MIN_VALUE, DAYS));
+        writeLockers.add((sl) -> tryWriteLockUninterrupted(sl, 0L, DAYS));
+        writeLockers.add((sl) -> sl.tryConvertToWriteLock(sl.tryOptimisticRead()));
+        return writeLockers;
+    }
+
+    List<BiConsumer<StampedLock, Long>> writeUnlockers() {
+        List<BiConsumer<StampedLock, Long>> writeUnlockers = new ArrayList<>();
+        writeUnlockers.add((sl, stamp) -> sl.unlockWrite(stamp));
+        writeUnlockers.add((sl, stamp) -> assertTrue(sl.tryUnlockWrite()));
+        writeUnlockers.add((sl, stamp) -> sl.asWriteLock().unlock());
+        writeUnlockers.add((sl, stamp) -> sl.unlock(stamp));
+        writeUnlockers.add((sl, stamp) -> assertValid(sl, sl.tryConvertToOptimisticRead(stamp)));
+        return writeUnlockers;
     }
 
     /**
      * Constructed StampedLock is in unlocked state
      */
     public void testConstructor() {
-        StampedLock lock;
-        lock = new StampedLock();
-        assertFalse(lock.isWriteLocked());
-        assertFalse(lock.isReadLocked());
-        assertEquals(lock.getReadLockCount(), 0);
+        assertUnlocked(new StampedLock());
     }
 
     /**
-     * write-locking and read-locking an unlocked lock succeed
+     * write-locking, then unlocking, an unlocked lock succeed
      */
-    public void testLock() {
+    public void testWriteLock_lockUnlock() {
         StampedLock lock = new StampedLock();
-        assertFalse(lock.isWriteLocked());
-        assertFalse(lock.isReadLocked());
-        assertEquals(lock.getReadLockCount(), 0);
-        long s = lock.writeLock();
-        assertTrue(lock.isWriteLocked());
-        assertFalse(lock.isReadLocked());
-        assertEquals(lock.getReadLockCount(), 0);
-        lock.unlockWrite(s);
-        assertFalse(lock.isWriteLocked());
-        assertFalse(lock.isReadLocked());
-        assertEquals(lock.getReadLockCount(), 0);
-        long rs = lock.readLock();
-        assertFalse(lock.isWriteLocked());
-        assertTrue(lock.isReadLocked());
-        assertEquals(lock.getReadLockCount(), 1);
-        lock.unlockRead(rs);
-        assertFalse(lock.isWriteLocked());
-        assertFalse(lock.isReadLocked());
-        assertEquals(lock.getReadLockCount(), 0);
-    }
 
-    /**
-     * unlock releases either a read or write lock
-     */
-    public void testUnlock() {
-        StampedLock lock = new StampedLock();
-        assertFalse(lock.isWriteLocked());
-        assertFalse(lock.isReadLocked());
-        assertEquals(lock.getReadLockCount(), 0);
-        long s = lock.writeLock();
-        assertTrue(lock.isWriteLocked());
-        assertFalse(lock.isReadLocked());
-        assertEquals(lock.getReadLockCount(), 0);
-        lock.unlock(s);
-        assertFalse(lock.isWriteLocked());
-        assertFalse(lock.isReadLocked());
-        assertEquals(lock.getReadLockCount(), 0);
-        long rs = lock.readLock();
-        assertFalse(lock.isWriteLocked());
-        assertTrue(lock.isReadLocked());
-        assertEquals(lock.getReadLockCount(), 1);
-        lock.unlock(rs);
-        assertFalse(lock.isWriteLocked());
-        assertFalse(lock.isReadLocked());
-        assertEquals(lock.getReadLockCount(), 0);
+        for (Function<StampedLock, Long> writeLocker : writeLockers())
+        for (BiConsumer<StampedLock, Long> writeUnlocker : writeUnlockers()) {
+            assertFalse(lock.isWriteLocked());
+            assertFalse(lock.isReadLocked());
+            assertEquals(0, lock.getReadLockCount());
+
+            long s = writeLocker.apply(lock);
+            assertValid(lock, s);
+            assertTrue(lock.isWriteLocked());
+            assertFalse(lock.isReadLocked());
+            assertEquals(0, lock.getReadLockCount());
+            writeUnlocker.accept(lock, s);
+            assertUnlocked(lock);
+        }
     }
 
     /**
-     * tryUnlockRead/Write succeeds if locked in associated mode else
-     * returns false
+     * read-locking, then unlocking, an unlocked lock succeed
      */
-    public void testTryUnlock() {
+    public void testReadLock_lockUnlock() {
         StampedLock lock = new StampedLock();
-        assertFalse(lock.isWriteLocked());
-        assertFalse(lock.isReadLocked());
-        assertEquals(lock.getReadLockCount(), 0);
-        long s = lock.writeLock();
-        assertTrue(lock.isWriteLocked());
-        assertFalse(lock.isReadLocked());
-        assertEquals(lock.getReadLockCount(), 0);
-        assertFalse(lock.tryUnlockRead());
-        assertTrue(lock.tryUnlockWrite());
-        assertFalse(lock.tryUnlockWrite());
-        assertFalse(lock.tryUnlockRead());
-        assertFalse(lock.isWriteLocked());
-        assertFalse(lock.isReadLocked());
-        assertEquals(lock.getReadLockCount(), 0);
-        long rs = lock.readLock();
-        assertFalse(lock.isWriteLocked());
-        assertTrue(lock.isReadLocked());
-        assertEquals(lock.getReadLockCount(), 1);
-        assertFalse(lock.tryUnlockWrite());
-        assertTrue(lock.tryUnlockRead());
-        assertFalse(lock.tryUnlockRead());
-        assertFalse(lock.tryUnlockWrite());
-        assertFalse(lock.isWriteLocked());
-        assertFalse(lock.isReadLocked());
-        assertEquals(lock.getReadLockCount(), 0);
-    }
 
-    /**
-     * write-unlocking an unlocked lock throws IllegalMonitorStateException
-     */
-    public void testWriteUnlock_IMSE() {
-        StampedLock lock = new StampedLock();
-        try {
-            lock.unlockWrite(0L);
-            shouldThrow();
-        } catch (IllegalMonitorStateException success) {}
+        for (Function<StampedLock, Long> readLocker : readLockers())
+        for (BiConsumer<StampedLock, Long> readUnlocker : readUnlockers()) {
+            long s = 42;
+            for (int i = 0; i < 2; i++) {
+                s = assertValid(lock, readLocker.apply(lock));
+                assertFalse(lock.isWriteLocked());
+                assertTrue(lock.isReadLocked());
+                assertEquals(i + 1, lock.getReadLockCount());
+            }
+            for (int i = 0; i < 2; i++) {
+                assertFalse(lock.isWriteLocked());
+                assertTrue(lock.isReadLocked());
+                assertEquals(2 - i, lock.getReadLockCount());
+                readUnlocker.accept(lock, s);
+            }
+            assertUnlocked(lock);
+        }
     }
 
     /**
-     * write-unlocking an unlocked lock throws IllegalMonitorStateException
+     * tryUnlockWrite fails if not write locked
      */
-    public void testWriteUnlock_IMSE2() {
+    public void testTryUnlockWrite_failure() {
         StampedLock lock = new StampedLock();
-        long s = lock.writeLock();
-        lock.unlockWrite(s);
-        try {
-            lock.unlockWrite(s);
-            shouldThrow();
-        } catch (IllegalMonitorStateException success) {}
-    }
+        assertFalse(lock.tryUnlockWrite());
 
-    /**
-     * write-unlocking after readlock throws IllegalMonitorStateException
-     */
-    public void testWriteUnlock_IMSE3() {
-        StampedLock lock = new StampedLock();
-        long s = lock.readLock();
-        try {
-            lock.unlockWrite(s);
-            shouldThrow();
-        } catch (IllegalMonitorStateException success) {}
+        for (Function<StampedLock, Long> readLocker : readLockers())
+        for (BiConsumer<StampedLock, Long> readUnlocker : readUnlockers()) {
+            long s = assertValid(lock, readLocker.apply(lock));
+            assertFalse(lock.tryUnlockWrite());
+            assertTrue(lock.isReadLocked());
+            readUnlocker.accept(lock, s);
+            assertUnlocked(lock);
+        }
     }
 
     /**
-     * read-unlocking an unlocked lock throws IllegalMonitorStateException
+     * tryUnlockRead fails if not read locked
      */
-    public void testReadUnlock_IMSE() {
+    public void testTryUnlockRead_failure() {
         StampedLock lock = new StampedLock();
-        long s = lock.readLock();
-        lock.unlockRead(s);
-        try {
-            lock.unlockRead(s);
-            shouldThrow();
-        } catch (IllegalMonitorStateException success) {}
+        assertFalse(lock.tryUnlockRead());
+
+        for (Function<StampedLock, Long> writeLocker : writeLockers())
+        for (BiConsumer<StampedLock, Long> writeUnlocker : writeUnlockers()) {
+            long s = writeLocker.apply(lock);
+            assertFalse(lock.tryUnlockRead());
+            assertTrue(lock.isWriteLocked());
+            writeUnlocker.accept(lock, s);
+            assertUnlocked(lock);
+        }
     }
 
     /**
-     * read-unlocking an unlocked lock throws IllegalMonitorStateException
-     */
-    public void testReadUnlock_IMSE2() {
-        StampedLock lock = new StampedLock();
-        try {
-            lock.unlockRead(0L);
-            shouldThrow();
-        } catch (IllegalMonitorStateException success) {}
-    }
-
-    /**
-     * read-unlocking after writeLock throws IllegalMonitorStateException
-     */
-    public void testReadUnlock_IMSE3() {
-        StampedLock lock = new StampedLock();
-        long s = lock.writeLock();
-        try {
-            lock.unlockRead(s);
-            shouldThrow();
-        } catch (IllegalMonitorStateException success) {}
-    }
-
-    /**
-     * validate(0) fails
+     * validate(0L) fails
      */
     public void testValidate0() {
         StampedLock lock = new StampedLock();
@@ -265,29 +248,24 @@
     }
 
     /**
-     * A stamp obtained from a successful lock operation validates
+     * A stamp obtained from a successful lock operation validates while the lock is held
      */
     public void testValidate() throws InterruptedException {
         StampedLock lock = new StampedLock();
-        long s = lock.writeLock();
-        assertTrue(lock.validate(s));
-        lock.unlockWrite(s);
-        s = lock.readLock();
-        assertTrue(lock.validate(s));
-        lock.unlockRead(s);
-        assertTrue((s = lock.tryWriteLock()) != 0L);
-        assertTrue(lock.validate(s));
-        lock.unlockWrite(s);
-        assertTrue((s = lock.tryReadLock()) != 0L);
-        assertTrue(lock.validate(s));
-        lock.unlockRead(s);
-        assertTrue((s = lock.tryWriteLock(100L, MILLISECONDS)) != 0L);
-        assertTrue(lock.validate(s));
-        lock.unlockWrite(s);
-        assertTrue((s = lock.tryReadLock(100L, MILLISECONDS)) != 0L);
-        assertTrue(lock.validate(s));
-        lock.unlockRead(s);
-        assertTrue((s = lock.tryOptimisticRead()) != 0L);
+
+        for (Function<StampedLock, Long> readLocker : readLockers())
+        for (BiConsumer<StampedLock, Long> readUnlocker : readUnlockers()) {
+            long s = assertNonZero(readLocker.apply(lock));
+            assertTrue(lock.validate(s));
+            readUnlocker.accept(lock, s);
+        }
+
+        for (Function<StampedLock, Long> writeLocker : writeLockers())
+        for (BiConsumer<StampedLock, Long> writeUnlocker : writeUnlockers()) {
+            long s = assertNonZero(writeLocker.apply(lock));
+            assertTrue(lock.validate(s));
+            writeUnlocker.accept(lock, s);
+        }
     }
 
     /**
@@ -295,124 +273,190 @@
      */
     public void testValidate2() throws InterruptedException {
         StampedLock lock = new StampedLock();
-        long s;
-        assertTrue((s = lock.writeLock()) != 0L);
+        long s = assertNonZero(lock.writeLock());
         assertTrue(lock.validate(s));
         assertFalse(lock.validate(lock.tryWriteLock()));
-        assertFalse(lock.validate(lock.tryWriteLock(10L, MILLISECONDS)));
+        assertFalse(lock.validate(lock.tryWriteLock(0L, SECONDS)));
         assertFalse(lock.validate(lock.tryReadLock()));
-        assertFalse(lock.validate(lock.tryReadLock(10L, MILLISECONDS)));
+        assertFalse(lock.validate(lock.tryReadLock(0L, SECONDS)));
         assertFalse(lock.validate(lock.tryOptimisticRead()));
         lock.unlockWrite(s);
     }
 
-    /**
-     * writeLockInterruptibly is interruptible
-     */
-    public void testWriteLockInterruptibly_Interruptible()
-            throws InterruptedException {
-        final CountDownLatch running = new CountDownLatch(1);
-        final StampedLock lock = new StampedLock();
-        long s = lock.writeLock();
-        Thread t = newStartedThread(new CheckedInterruptedRunnable() {
-            public void realRun() throws InterruptedException {
-                running.countDown();
-                lock.writeLockInterruptibly();
-            }});
-
-        running.await();
-        waitForThreadToEnterWaitState(t, 100);
-        t.interrupt();
-        awaitTermination(t);
-        releaseWriteLock(lock, s);
+    void assertThrowInterruptedExceptionWhenPreInterrupted(Action[] actions) {
+        for (Action action : actions) {
+            Thread.currentThread().interrupt();
+            try {
+                action.run();
+                shouldThrow();
+            }
+            catch (InterruptedException success) {}
+            catch (Throwable fail) { threadUnexpectedException(fail); }
+            assertFalse(Thread.interrupted());
+        }
     }
 
     /**
-     * timed tryWriteLock is interruptible
+     * interruptible operations throw InterruptedException when pre-interrupted
      */
-    public void testWriteTryLock_Interruptible() throws InterruptedException {
+    public void testInterruptibleOperationsThrowInterruptedExceptionWhenPreInterrupted() {
+        final CountDownLatch running = new CountDownLatch(1);
+        final StampedLock lock = new StampedLock();
+
+        Action[] interruptibleLockActions = {
+            () -> lock.writeLockInterruptibly(),
+            () -> lock.tryWriteLock(Long.MIN_VALUE, DAYS),
+            () -> lock.tryWriteLock(Long.MAX_VALUE, DAYS),
+            () -> lock.readLockInterruptibly(),
+            () -> lock.tryReadLock(Long.MIN_VALUE, DAYS),
+            () -> lock.tryReadLock(Long.MAX_VALUE, DAYS),
+            () -> lock.asWriteLock().lockInterruptibly(),
+            () -> lock.asWriteLock().tryLock(0L, DAYS),
+            () -> lock.asWriteLock().tryLock(Long.MAX_VALUE, DAYS),
+            () -> lock.asReadLock().lockInterruptibly(),
+            () -> lock.asReadLock().tryLock(0L, DAYS),
+            () -> lock.asReadLock().tryLock(Long.MAX_VALUE, DAYS),
+        };
+        shuffle(interruptibleLockActions);
+
+        assertThrowInterruptedExceptionWhenPreInterrupted(interruptibleLockActions);
+        {
+            long s = lock.writeLock();
+            assertThrowInterruptedExceptionWhenPreInterrupted(interruptibleLockActions);
+            lock.unlockWrite(s);
+        }
+        {
+            long s = lock.readLock();
+            assertThrowInterruptedExceptionWhenPreInterrupted(interruptibleLockActions);
+            lock.unlockRead(s);
+        }
+    }
+
+    void assertThrowInterruptedExceptionWhenInterrupted(Action[] actions) {
+        int n = actions.length;
+        Future<?>[] futures = new Future<?>[n];
+        CountDownLatch threadsStarted = new CountDownLatch(n);
+        CountDownLatch done = new CountDownLatch(n);
+
+        for (int i = 0; i < n; i++) {
+            Action action = actions[i];
+            futures[i] = cachedThreadPool.submit(new CheckedRunnable() {
+                public void realRun() throws Throwable {
+                    threadsStarted.countDown();
+                    try {
+                        action.run();
+                        shouldThrow();
+                    }
+                    catch (InterruptedException success) {}
+                    catch (Throwable fail) { threadUnexpectedException(fail); }
+                    assertFalse(Thread.interrupted());
+                    done.countDown();
+                }});
+        }
+
+        await(threadsStarted);
+        assertEquals(n, done.getCount());
+        for (Future<?> future : futures) // Interrupt all the tasks
+            future.cancel(true);
+        await(done);
+    }
+
+    /**
+     * interruptible operations throw InterruptedException when write locked and interrupted
+     */
+    public void testInterruptibleOperationsThrowInterruptedExceptionWriteLockedInterrupted() {
         final CountDownLatch running = new CountDownLatch(1);
         final StampedLock lock = new StampedLock();
         long s = lock.writeLock();
-        Thread t = newStartedThread(new CheckedInterruptedRunnable() {
-            public void realRun() throws InterruptedException {
-                running.countDown();
-                lock.tryWriteLock(2 * LONG_DELAY_MS, MILLISECONDS);
-            }});
 
-        running.await();
-        waitForThreadToEnterWaitState(t, 100);
-        t.interrupt();
-        awaitTermination(t);
-        releaseWriteLock(lock, s);
+        Action[] interruptibleLockBlockingActions = {
+            () -> lock.writeLockInterruptibly(),
+            () -> lock.tryWriteLock(Long.MAX_VALUE, DAYS),
+            () -> lock.readLockInterruptibly(),
+            () -> lock.tryReadLock(Long.MAX_VALUE, DAYS),
+            () -> lock.asWriteLock().lockInterruptibly(),
+            () -> lock.asWriteLock().tryLock(Long.MAX_VALUE, DAYS),
+            () -> lock.asReadLock().lockInterruptibly(),
+            () -> lock.asReadLock().tryLock(Long.MAX_VALUE, DAYS),
+        };
+        shuffle(interruptibleLockBlockingActions);
+
+        assertThrowInterruptedExceptionWhenInterrupted(interruptibleLockBlockingActions);
     }
 
     /**
-     * readLockInterruptibly is interruptible
+     * interruptible operations throw InterruptedException when read locked and interrupted
      */
-    public void testReadLockInterruptibly_Interruptible()
-            throws InterruptedException {
+    public void testInterruptibleOperationsThrowInterruptedExceptionReadLockedInterrupted() {
         final CountDownLatch running = new CountDownLatch(1);
         final StampedLock lock = new StampedLock();
-        long s = lock.writeLock();
-        Thread t = newStartedThread(new CheckedInterruptedRunnable() {
-            public void realRun() throws InterruptedException {
-                running.countDown();
-                lock.readLockInterruptibly();
-            }});
+        long s = lock.readLock();
 
-        running.await();
-        waitForThreadToEnterWaitState(t, 100);
-        t.interrupt();
-        awaitTermination(t);
-        releaseWriteLock(lock, s);
+        Action[] interruptibleLockBlockingActions = {
+            () -> lock.writeLockInterruptibly(),
+            () -> lock.tryWriteLock(Long.MAX_VALUE, DAYS),
+            () -> lock.asWriteLock().lockInterruptibly(),
+            () -> lock.asWriteLock().tryLock(Long.MAX_VALUE, DAYS),
+        };
+        shuffle(interruptibleLockBlockingActions);
+
+        assertThrowInterruptedExceptionWhenInterrupted(interruptibleLockBlockingActions);
     }
 
     /**
-     * timed tryReadLock is interruptible
+     * Non-interruptible operations ignore and preserve interrupt status
      */
-    public void testReadTryLock_Interruptible() throws InterruptedException {
-        final CountDownLatch running = new CountDownLatch(1);
+    public void testNonInterruptibleOperationsIgnoreInterrupts() {
         final StampedLock lock = new StampedLock();
-        long s = lock.writeLock();
-        Thread t = newStartedThread(new CheckedInterruptedRunnable() {
-            public void realRun() throws InterruptedException {
-                running.countDown();
-                lock.tryReadLock(2 * LONG_DELAY_MS, MILLISECONDS);
-            }});
+        Thread.currentThread().interrupt();
+
+        for (BiConsumer<StampedLock, Long> readUnlocker : readUnlockers()) {
+            long s = assertValid(lock, lock.readLock());
+            readUnlocker.accept(lock, s);
+            s = assertValid(lock, lock.tryReadLock());
+            readUnlocker.accept(lock, s);
+        }
+
+        lock.asReadLock().lock();
+        lock.asReadLock().unlock();
 
-        running.await();
-        waitForThreadToEnterWaitState(t, 100);
-        t.interrupt();
-        awaitTermination(t);
-        releaseWriteLock(lock, s);
+        for (BiConsumer<StampedLock, Long> writeUnlocker : writeUnlockers()) {
+            long s = assertValid(lock, lock.writeLock());
+            writeUnlocker.accept(lock, s);
+            s = assertValid(lock, lock.tryWriteLock());
+            writeUnlocker.accept(lock, s);
+        }
+
+        lock.asWriteLock().lock();
+        lock.asWriteLock().unlock();
+
+        assertTrue(Thread.interrupted());
     }
 
     /**
      * tryWriteLock on an unlocked lock succeeds
      */
-    public void testWriteTryLock() {
+    public void testTryWriteLock() {
         final StampedLock lock = new StampedLock();
         long s = lock.tryWriteLock();
         assertTrue(s != 0L);
         assertTrue(lock.isWriteLocked());
-        long s2 = lock.tryWriteLock();
-        assertEquals(s2, 0L);
+        assertEquals(0L, lock.tryWriteLock());
         releaseWriteLock(lock, s);
     }
 
     /**
      * tryWriteLock fails if locked
      */
-    public void testWriteTryLockWhenLocked() {
+    public void testTryWriteLockWhenLocked() {
         final StampedLock lock = new StampedLock();
         long s = lock.writeLock();
         Thread t = newStartedThread(new CheckedRunnable() {
             public void realRun() {
-                long ws = lock.tryWriteLock();
-                assertTrue(ws == 0L);
+                assertEquals(0L, lock.tryWriteLock());
             }});
 
+        assertEquals(0L, lock.tryWriteLock());
         awaitTermination(t);
         releaseWriteLock(lock, s);
     }
@@ -420,15 +464,15 @@
     /**
      * tryReadLock fails if write-locked
      */
-    public void testReadTryLockWhenLocked() {
+    public void testTryReadLockWhenLocked() {
         final StampedLock lock = new StampedLock();
         long s = lock.writeLock();
         Thread t = newStartedThread(new CheckedRunnable() {
             public void realRun() {
-                long rs = lock.tryReadLock();
-                assertEquals(rs, 0L);
+                assertEquals(0L, lock.tryReadLock());
             }});
 
+        assertEquals(0L, lock.tryReadLock());
         awaitTermination(t);
         releaseWriteLock(lock, s);
     }
@@ -442,13 +486,20 @@
         Thread t = newStartedThread(new CheckedRunnable() {
             public void realRun() throws InterruptedException {
                 long s2 = lock.tryReadLock();
-                assertTrue(s2 != 0L);
+                assertValid(lock, s2);
                 lock.unlockRead(s2);
                 long s3 = lock.tryReadLock(LONG_DELAY_MS, MILLISECONDS);
-                assertTrue(s3 != 0L);
+                assertValid(lock, s3);
                 lock.unlockRead(s3);
                 long s4 = lock.readLock();
+                assertValid(lock, s4);
                 lock.unlockRead(s4);
+                lock.asReadLock().lock();
+                lock.asReadLock().unlock();
+                lock.asReadLock().lockInterruptibly();
+                lock.asReadLock().unlock();
+                lock.asReadLock().tryLock(Long.MIN_VALUE, DAYS);
+                lock.asReadLock().unlock();
             }});
 
         awaitTermination(t);
@@ -470,7 +521,7 @@
             }});
 
         running.await();
-        waitForThreadToEnterWaitState(t, 100);
+        waitForThreadToEnterWaitState(t, MEDIUM_DELAY_MS);
         assertFalse(lock.isWriteLocked());
         lock.unlockRead(rs);
         awaitTermination(t);
@@ -497,6 +548,7 @@
                 lock.unlockWrite(ws);
             }});
 
+        assertTrue(lock.isReadLocked());
         assertFalse(lock.isWriteLocked());
         lock.unlockRead(s);
         awaitTermination(t2);
@@ -508,25 +560,31 @@
      */
     public void testReadAfterWriteLock() {
         final StampedLock lock = new StampedLock();
+        final CountDownLatch threadsStarted = new CountDownLatch(2);
         final long s = lock.writeLock();
         Thread t1 = newStartedThread(new CheckedRunnable() {
             public void realRun() {
+                threadsStarted.countDown();
                 long rs = lock.readLock();
                 lock.unlockRead(rs);
             }});
         Thread t2 = newStartedThread(new CheckedRunnable() {
             public void realRun() {
+                threadsStarted.countDown();
                 long rs = lock.readLock();
                 lock.unlockRead(rs);
             }});
 
+        await(threadsStarted);
+        waitForThreadToEnterWaitState(t1, MEDIUM_DELAY_MS);
+        waitForThreadToEnterWaitState(t2, MEDIUM_DELAY_MS);
         releaseWriteLock(lock, s);
         awaitTermination(t1);
         awaitTermination(t2);
     }
 
     /**
-     * tryReadLock succeeds if readlocked but not writelocked
+     * tryReadLock succeeds if read locked but not write locked
      */
     public void testTryLockWhenReadLocked() {
         final StampedLock lock = new StampedLock();
@@ -534,7 +592,7 @@
         Thread t = newStartedThread(new CheckedRunnable() {
             public void realRun() {
                 long rs = lock.tryReadLock();
-                threadAssertTrue(rs != 0L);
+                assertValid(lock, rs);
                 lock.unlockRead(rs);
             }});
 
@@ -543,15 +601,14 @@
     }
 
     /**
-     * tryWriteLock fails when readlocked
+     * tryWriteLock fails when read locked
      */
-    public void testWriteTryLockWhenReadLocked() {
+    public void testTryWriteLockWhenReadLocked() {
         final StampedLock lock = new StampedLock();
         long s = lock.readLock();
         Thread t = newStartedThread(new CheckedRunnable() {
             public void realRun() {
-                long ws = lock.tryWriteLock();
-                threadAssertEquals(ws, 0L);
+                threadAssertEquals(0L, lock.tryWriteLock());
             }});
 
         awaitTermination(t);
@@ -559,86 +616,82 @@
     }
 
     /**
-     * timed tryWriteLock times out if locked
+     * timed lock operations time out if lock not available
      */
-    public void testWriteTryLock_Timeout() {
+    public void testTimedLock_Timeout() throws Exception {
+        ArrayList<Future<?>> futures = new ArrayList<>();
+
+        // Write locked
         final StampedLock lock = new StampedLock();
-        long s = lock.writeLock();
-        Thread t = newStartedThread(new CheckedRunnable() {
+        long stamp = lock.writeLock();
+        assertEquals(0L, lock.tryReadLock(0L, DAYS));
+        assertEquals(0L, lock.tryReadLock(Long.MIN_VALUE, DAYS));
+        assertFalse(lock.asReadLock().tryLock(0L, DAYS));
+        assertFalse(lock.asReadLock().tryLock(Long.MIN_VALUE, DAYS));
+        assertEquals(0L, lock.tryWriteLock(0L, DAYS));
+        assertEquals(0L, lock.tryWriteLock(Long.MIN_VALUE, DAYS));
+        assertFalse(lock.asWriteLock().tryLock(0L, DAYS));
+        assertFalse(lock.asWriteLock().tryLock(Long.MIN_VALUE, DAYS));
+
+        futures.add(cachedThreadPool.submit(new CheckedRunnable() {
+            public void realRun() throws InterruptedException {
+                long startTime = System.nanoTime();
+                assertEquals(0L, lock.tryWriteLock(timeoutMillis(), MILLISECONDS));
+                assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
+            }}));
+
+        futures.add(cachedThreadPool.submit(new CheckedRunnable() {
             public void realRun() throws InterruptedException {
                 long startTime = System.nanoTime();
-                long timeoutMillis = 10;
-                long ws = lock.tryWriteLock(timeoutMillis, MILLISECONDS);
-                assertEquals(ws, 0L);
-                assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
-            }});
+                assertEquals(0L, lock.tryReadLock(timeoutMillis(), MILLISECONDS));
+                assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
+            }}));
+
+        // Read locked
+        final StampedLock lock2 = new StampedLock();
+        long stamp2 = lock2.readLock();
+        assertEquals(0L, lock2.tryWriteLock(0L, DAYS));
+        assertEquals(0L, lock2.tryWriteLock(Long.MIN_VALUE, DAYS));
+        assertFalse(lock2.asWriteLock().tryLock(0L, DAYS));
+        assertFalse(lock2.asWriteLock().tryLock(Long.MIN_VALUE, DAYS));
 
-        awaitTermination(t);
+        futures.add(cachedThreadPool.submit(new CheckedRunnable() {
+            public void realRun() throws InterruptedException {
+                long startTime = System.nanoTime();
+                assertEquals(0L, lock2.tryWriteLock(timeoutMillis(), MILLISECONDS));
+                assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
+            }}));
+
+        for (Future<?> future : futures)
+            assertNull(future.get());
+
+        releaseWriteLock(lock, stamp);
+        releaseReadLock(lock2, stamp2);
+    }
+
+    /**
+     * writeLockInterruptibly succeeds if unlocked
+     */
+    public void testWriteLockInterruptibly() throws InterruptedException {
+        final StampedLock lock = new StampedLock();
+        long s = lock.writeLockInterruptibly();
+        assertTrue(lock.isWriteLocked());
         releaseWriteLock(lock, s);
     }
 
     /**
-     * timed tryReadLock times out if write-locked
-     */
-    public void testReadTryLock_Timeout() {
-        final StampedLock lock = new StampedLock();
-        long s = lock.writeLock();
-        Thread t = newStartedThread(new CheckedRunnable() {
-            public void realRun() throws InterruptedException {
-                long startTime = System.nanoTime();
-                long timeoutMillis = 10;
-                long rs = lock.tryReadLock(timeoutMillis, MILLISECONDS);
-                assertEquals(rs, 0L);
-                assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
-            }});
-
-        awaitTermination(t);
-        assertTrue(lock.isWriteLocked());
-        lock.unlockWrite(s);
-    }
-
-    /**
-     * writeLockInterruptibly succeeds if unlocked, else is interruptible
-     */
-    public void testWriteLockInterruptibly() throws InterruptedException {
-        final CountDownLatch running = new CountDownLatch(1);
-        final StampedLock lock = new StampedLock();
-        long s = lock.writeLockInterruptibly();
-        Thread t = newStartedThread(new CheckedInterruptedRunnable() {
-            public void realRun() throws InterruptedException {
-                running.countDown();
-                lock.writeLockInterruptibly();
-            }});
-
-        running.await();
-        waitForThreadToEnterWaitState(t, 100);
-        t.interrupt();
-        assertTrue(lock.isWriteLocked());
-        awaitTermination(t);
-        releaseWriteLock(lock, s);
-    }
-
-    /**
-     * readLockInterruptibly succeeds if lock free else is interruptible
+     * readLockInterruptibly succeeds if lock free
      */
     public void testReadLockInterruptibly() throws InterruptedException {
-        final CountDownLatch running = new CountDownLatch(1);
         final StampedLock lock = new StampedLock();
-        long s;
-        s = lock.readLockInterruptibly();
+
+        long s = assertValid(lock, lock.readLockInterruptibly());
+        assertTrue(lock.isReadLocked());
         lock.unlockRead(s);
-        s = lock.writeLockInterruptibly();
-        Thread t = newStartedThread(new CheckedInterruptedRunnable() {
-            public void realRun() throws InterruptedException {
-                running.countDown();
-                lock.readLockInterruptibly();
-            }});
 
-        running.await();
-        waitForThreadToEnterWaitState(t, 100);
-        t.interrupt();
-        awaitTermination(t);
-        releaseWriteLock(lock, s);
+        lock.asReadLock().lockInterruptibly();
+        assertTrue(lock.isReadLocked());
+        lock.asReadLock().unlock();
     }
 
     /**
@@ -670,54 +723,39 @@
     }
 
     /**
-     * tryOptimisticRead succeeds and validates if unlocked, fails if locked
+     * tryOptimisticRead succeeds and validates if unlocked, fails if
+     * exclusively locked
      */
     public void testValidateOptimistic() throws InterruptedException {
         StampedLock lock = new StampedLock();
-        long s, p;
-        assertTrue((p = lock.tryOptimisticRead()) != 0L);
-        assertTrue(lock.validate(p));
-        assertTrue((s = lock.writeLock()) != 0L);
-        assertFalse((p = lock.tryOptimisticRead()) != 0L);
-        assertTrue(lock.validate(s));
-        lock.unlockWrite(s);
-        assertTrue((p = lock.tryOptimisticRead()) != 0L);
-        assertTrue(lock.validate(p));
-        assertTrue((s = lock.readLock()) != 0L);
-        assertTrue(lock.validate(s));
-        assertTrue((p = lock.tryOptimisticRead()) != 0L);
-        assertTrue(lock.validate(p));
-        lock.unlockRead(s);
-        assertTrue((s = lock.tryWriteLock()) != 0L);
-        assertTrue(lock.validate(s));
-        assertFalse((p = lock.tryOptimisticRead()) != 0L);
-        lock.unlockWrite(s);
-        assertTrue((s = lock.tryReadLock()) != 0L);
-        assertTrue(lock.validate(s));
-        assertTrue((p = lock.tryOptimisticRead()) != 0L);
-        lock.unlockRead(s);
-        assertTrue(lock.validate(p));
-        assertTrue((s = lock.tryWriteLock(100L, MILLISECONDS)) != 0L);
-        assertFalse((p = lock.tryOptimisticRead()) != 0L);
-        assertTrue(lock.validate(s));
-        lock.unlockWrite(s);
-        assertTrue((s = lock.tryReadLock(100L, MILLISECONDS)) != 0L);
-        assertTrue(lock.validate(s));
-        assertTrue((p = lock.tryOptimisticRead()) != 0L);
-        lock.unlockRead(s);
-        assertTrue((p = lock.tryOptimisticRead()) != 0L);
+
+        assertValid(lock, lock.tryOptimisticRead());
+
+        for (Function<StampedLock, Long> writeLocker : writeLockers()) {
+            long s = assertValid(lock, writeLocker.apply(lock));
+            assertEquals(0L, lock.tryOptimisticRead());
+            releaseWriteLock(lock, s);
+        }
+
+        for (Function<StampedLock, Long> readLocker : readLockers()) {
+            long s = assertValid(lock, readLocker.apply(lock));
+            long p = assertValid(lock, lock.tryOptimisticRead());
+            releaseReadLock(lock, s);
+            assertTrue(lock.validate(p));
+        }
+
+        assertValid(lock, lock.tryOptimisticRead());
     }
 
     /**
      * tryOptimisticRead stamp does not validate if a write lock intervenes
      */
     public void testValidateOptimisticWriteLocked() {
-        StampedLock lock = new StampedLock();
-        long s, p;
-        assertTrue((p = lock.tryOptimisticRead()) != 0L);
-        assertTrue((s = lock.writeLock()) != 0L);
+        final StampedLock lock = new StampedLock();
+        final long p = assertValid(lock, lock.tryOptimisticRead());
+        final long s = assertValid(lock, lock.writeLock());
         assertFalse(lock.validate(p));
-        assertFalse((p = lock.tryOptimisticRead()) != 0L);
+        assertEquals(0L, lock.tryOptimisticRead());
         assertTrue(lock.validate(s));
         lock.unlockWrite(s);
     }
@@ -730,8 +768,8 @@
             throws InterruptedException {
         final CountDownLatch running = new CountDownLatch(1);
         final StampedLock lock = new StampedLock();
-        long s, p;
-        assertTrue((p = lock.tryOptimisticRead()) != 0L);
+        final long p = assertValid(lock, lock.tryOptimisticRead());
+
         Thread t = newStartedThread(new CheckedInterruptedRunnable() {
             public void realRun() throws InterruptedException {
                 lock.writeLockInterruptibly();
@@ -741,228 +779,209 @@
 
         running.await();
         assertFalse(lock.validate(p));
-        assertFalse((p = lock.tryOptimisticRead()) != 0L);
+        assertEquals(0L, lock.tryOptimisticRead());
         t.interrupt();
         awaitTermination(t);
     }
 
     /**
-     * tryConvertToOptimisticRead succeeds and validates if successfully locked,
+     * tryConvertToOptimisticRead succeeds and validates if successfully locked
      */
     public void testTryConvertToOptimisticRead() throws InterruptedException {
         StampedLock lock = new StampedLock();
-        long s, p;
+        long s, p, q;
         assertEquals(0L, lock.tryConvertToOptimisticRead(0L));
 
-        assertTrue((s = lock.tryOptimisticRead()) != 0L);
+        s = assertValid(lock, lock.tryOptimisticRead());
         assertEquals(s, lock.tryConvertToOptimisticRead(s));
         assertTrue(lock.validate(s));
 
-        assertTrue((p = lock.readLock()) != 0L);
-        assertTrue((s = lock.tryOptimisticRead()) != 0L);
-        assertEquals(s, lock.tryConvertToOptimisticRead(s));
-        assertTrue(lock.validate(s));
-        lock.unlockRead(p);
-
-        assertTrue((s = lock.writeLock()) != 0L);
-        assertTrue((p = lock.tryConvertToOptimisticRead(s)) != 0L);
-        assertTrue(lock.validate(p));
-
-        assertTrue((s = lock.readLock()) != 0L);
-        assertTrue(lock.validate(s));
-        assertTrue((p = lock.tryConvertToOptimisticRead(s)) != 0L);
-        assertTrue(lock.validate(p));
+        for (Function<StampedLock, Long> writeLocker : writeLockers()) {
+            s = assertValid(lock, writeLocker.apply(lock));
+            p = assertValid(lock, lock.tryConvertToOptimisticRead(s));
+            assertFalse(lock.validate(s));
+            assertTrue(lock.validate(p));
+            assertUnlocked(lock);
+        }
 
-        assertTrue((s = lock.tryWriteLock()) != 0L);
-        assertTrue(lock.validate(s));
-        assertTrue((p = lock.tryConvertToOptimisticRead(s)) != 0L);
-        assertTrue(lock.validate(p));
-
-        assertTrue((s = lock.tryReadLock()) != 0L);
-        assertTrue(lock.validate(s));
-        assertTrue((p = lock.tryConvertToOptimisticRead(s)) != 0L);
-        assertTrue(lock.validate(p));
-
-        assertTrue((s = lock.tryWriteLock(100L, MILLISECONDS)) != 0L);
-        assertTrue((p = lock.tryConvertToOptimisticRead(s)) != 0L);
-        assertTrue(lock.validate(p));
-
-        assertTrue((s = lock.tryReadLock(100L, MILLISECONDS)) != 0L);
-        assertTrue(lock.validate(s));
-        assertTrue((p = lock.tryConvertToOptimisticRead(s)) != 0L);
-        assertTrue(lock.validate(p));
+        for (Function<StampedLock, Long> readLocker : readLockers()) {
+            s = assertValid(lock, readLocker.apply(lock));
+            q = assertValid(lock, lock.tryOptimisticRead());
+            assertEquals(q, lock.tryConvertToOptimisticRead(q));
+            assertTrue(lock.validate(q));
+            assertTrue(lock.isReadLocked());
+            p = assertValid(lock, lock.tryConvertToOptimisticRead(s));
+            assertTrue(lock.validate(p));
+            assertTrue(lock.validate(s));
+            assertUnlocked(lock);
+            assertEquals(q, lock.tryConvertToOptimisticRead(q));
+            assertTrue(lock.validate(q));
+        }
     }
 
     /**
-     * tryConvertToReadLock succeeds and validates if successfully locked
-     * or lock free;
+     * tryConvertToReadLock succeeds for valid stamps
      */
     public void testTryConvertToReadLock() throws InterruptedException {
         StampedLock lock = new StampedLock();
         long s, p;
 
-        assertFalse((p = lock.tryConvertToReadLock(0L)) != 0L);
+        assertEquals(0L, lock.tryConvertToReadLock(0L));
 
-        assertTrue((s = lock.tryOptimisticRead()) != 0L);
-        assertTrue((p = lock.tryConvertToReadLock(s)) != 0L);
+        s = assertValid(lock, lock.tryOptimisticRead());
+        p = assertValid(lock, lock.tryConvertToReadLock(s));
         assertTrue(lock.isReadLocked());
         assertEquals(1, lock.getReadLockCount());
+        assertTrue(lock.validate(s));
         lock.unlockRead(p);
 
-        assertTrue((s = lock.tryOptimisticRead()) != 0L);
+        s = assertValid(lock, lock.tryOptimisticRead());
         lock.readLock();
-        assertTrue((p = lock.tryConvertToReadLock(s)) != 0L);
+        p = assertValid(lock, lock.tryConvertToReadLock(s));
         assertTrue(lock.isReadLocked());
         assertEquals(2, lock.getReadLockCount());
         lock.unlockRead(p);
         lock.unlockRead(p);
-
-        assertTrue((s = lock.writeLock()) != 0L);
-        assertTrue((p = lock.tryConvertToReadLock(s)) != 0L);
-        assertTrue(lock.validate(p));
-        assertTrue(lock.isReadLocked());
-        assertEquals(1, lock.getReadLockCount());
-        lock.unlockRead(p);
-
-        assertTrue((s = lock.readLock()) != 0L);
-        assertTrue(lock.validate(s));
-        assertEquals(s, lock.tryConvertToReadLock(s));
-        assertTrue(lock.validate(s));
-        assertTrue(lock.isReadLocked());
-        assertEquals(1, lock.getReadLockCount());
-        lock.unlockRead(s);
-
-        assertTrue((s = lock.tryWriteLock()) != 0L);
-        assertTrue(lock.validate(s));
-        assertTrue((p = lock.tryConvertToReadLock(s)) != 0L);
-        assertTrue(lock.validate(p));
-        assertEquals(1, lock.getReadLockCount());
-        lock.unlockRead(p);
+        assertUnlocked(lock);
 
-        assertTrue((s = lock.tryReadLock()) != 0L);
-        assertTrue(lock.validate(s));
-        assertEquals(s, lock.tryConvertToReadLock(s));
-        assertTrue(lock.validate(s));
-        assertTrue(lock.isReadLocked());
-        assertEquals(1, lock.getReadLockCount());
-        lock.unlockRead(s);
+        for (BiConsumer<StampedLock, Long> readUnlocker : readUnlockers()) {
+            for (Function<StampedLock, Long> writeLocker : writeLockers()) {
+                s = assertValid(lock, writeLocker.apply(lock));
+                p = assertValid(lock, lock.tryConvertToReadLock(s));
+                assertFalse(lock.validate(s));
+                assertTrue(lock.isReadLocked());
+                assertEquals(1, lock.getReadLockCount());
+                readUnlocker.accept(lock, p);
+            }
 
-        assertTrue((s = lock.tryWriteLock(100L, MILLISECONDS)) != 0L);
-        assertTrue((p = lock.tryConvertToReadLock(s)) != 0L);
-        assertTrue(lock.validate(p));
-        assertTrue(lock.isReadLocked());
-        assertEquals(1, lock.getReadLockCount());
-        lock.unlockRead(p);
-
-        assertTrue((s = lock.tryReadLock(100L, MILLISECONDS)) != 0L);
-        assertTrue(lock.validate(s));
-        assertEquals(s, lock.tryConvertToReadLock(s));
-        assertTrue(lock.validate(s));
-        assertTrue(lock.isReadLocked());
-        assertEquals(1, lock.getReadLockCount());
-        lock.unlockRead(s);
+            for (Function<StampedLock, Long> readLocker : readLockers()) {
+                s = assertValid(lock, readLocker.apply(lock));
+                assertEquals(s, lock.tryConvertToReadLock(s));
+                assertTrue(lock.validate(s));
+                assertTrue(lock.isReadLocked());
+                assertEquals(1, lock.getReadLockCount());
+                readUnlocker.accept(lock, s);
+            }
+        }
     }
 
     /**
-     * tryConvertToWriteLock succeeds and validates if successfully locked
-     * or lock free;
+     * tryConvertToWriteLock succeeds if lock available; fails if multiply read locked
      */
     public void testTryConvertToWriteLock() throws InterruptedException {
         StampedLock lock = new StampedLock();
         long s, p;
 
-        assertFalse((p = lock.tryConvertToWriteLock(0L)) != 0L);
+        assertEquals(0L, lock.tryConvertToWriteLock(0L));
 
         assertTrue((s = lock.tryOptimisticRead()) != 0L);
         assertTrue((p = lock.tryConvertToWriteLock(s)) != 0L);
         assertTrue(lock.isWriteLocked());
         lock.unlockWrite(p);
 
-        assertTrue((s = lock.writeLock()) != 0L);
-        assertEquals(s, lock.tryConvertToWriteLock(s));
-        assertTrue(lock.validate(s));
-        assertTrue(lock.isWriteLocked());
-        lock.unlockWrite(s);
-
-        assertTrue((s = lock.readLock()) != 0L);
-        assertTrue(lock.validate(s));
-        assertTrue((p = lock.tryConvertToWriteLock(s)) != 0L);
-        assertTrue(lock.validate(p));
-        assertTrue(lock.isWriteLocked());
-        lock.unlockWrite(p);
-
-        assertTrue((s = lock.tryWriteLock()) != 0L);
-        assertTrue(lock.validate(s));
-        assertEquals(s, lock.tryConvertToWriteLock(s));
-        assertTrue(lock.validate(s));
-        assertTrue(lock.isWriteLocked());
-        lock.unlockWrite(s);
+        for (BiConsumer<StampedLock, Long> writeUnlocker : writeUnlockers()) {
+            for (Function<StampedLock, Long> writeLocker : writeLockers()) {
+                s = assertValid(lock, writeLocker.apply(lock));
+                assertEquals(s, lock.tryConvertToWriteLock(s));
+                assertTrue(lock.validate(s));
+                assertTrue(lock.isWriteLocked());
+                writeUnlocker.accept(lock, s);
+            }
 
-        assertTrue((s = lock.tryReadLock()) != 0L);
-        assertTrue(lock.validate(s));
-        assertTrue((p = lock.tryConvertToWriteLock(s)) != 0L);
-        assertTrue(lock.validate(p));
-        assertTrue(lock.isWriteLocked());
-        lock.unlockWrite(p);
+            for (Function<StampedLock, Long> readLocker : readLockers()) {
+                s = assertValid(lock, readLocker.apply(lock));
+                p = assertValid(lock, lock.tryConvertToWriteLock(s));
+                assertFalse(lock.validate(s));
+                assertTrue(lock.validate(p));
+                assertTrue(lock.isWriteLocked());
+                writeUnlocker.accept(lock, p);
+            }
+        }
 
-        assertTrue((s = lock.tryWriteLock(100L, MILLISECONDS)) != 0L);
-        assertTrue((p = lock.tryConvertToWriteLock(s)) != 0L);
-        assertTrue(lock.validate(p));
-        assertTrue(lock.isWriteLocked());
-        lock.unlockWrite(p);
-
-        assertTrue((s = lock.tryReadLock(100L, MILLISECONDS)) != 0L);
-        assertTrue(lock.validate(s));
-        assertTrue((p = lock.tryConvertToWriteLock(s)) != 0L);
-        assertTrue(lock.validate(p));
-        assertTrue(lock.isWriteLocked());
-        lock.unlockWrite(p);
+        // failure if multiply read locked
+        for (Function<StampedLock, Long> readLocker : readLockers()) {
+            s = assertValid(lock, readLocker.apply(lock));
+            p = assertValid(lock, readLocker.apply(lock));
+            assertEquals(0L, lock.tryConvertToWriteLock(s));
+            assertTrue(lock.validate(s));
+            assertTrue(lock.validate(p));
+            assertEquals(2, lock.getReadLockCount());
+            lock.unlock(p);
+            lock.unlock(s);
+            assertUnlocked(lock);
+        }
     }
 
     /**
      * asWriteLock can be locked and unlocked
      */
-    public void testAsWriteLock() {
+    public void testAsWriteLock() throws Throwable {
         StampedLock sl = new StampedLock();
         Lock lock = sl.asWriteLock();
-        lock.lock();
-        assertFalse(lock.tryLock());
-        lock.unlock();
-        assertTrue(lock.tryLock());
+        for (Action locker : lockLockers(lock)) {
+            locker.run();
+            assertTrue(sl.isWriteLocked());
+            assertFalse(sl.isReadLocked());
+            assertFalse(lock.tryLock());
+            lock.unlock();
+            assertUnlocked(sl);
+        }
     }
 
     /**
      * asReadLock can be locked and unlocked
      */
-    public void testAsReadLock() {
+    public void testAsReadLock() throws Throwable {
         StampedLock sl = new StampedLock();
         Lock lock = sl.asReadLock();
-        lock.lock();
-        lock.unlock();
-        assertTrue(lock.tryLock());
+        for (Action locker : lockLockers(lock)) {
+            locker.run();
+            assertTrue(sl.isReadLocked());
+            assertFalse(sl.isWriteLocked());
+            assertEquals(1, sl.getReadLockCount());
+            locker.run();
+            assertTrue(sl.isReadLocked());
+            assertEquals(2, sl.getReadLockCount());
+            lock.unlock();
+            lock.unlock();
+            assertUnlocked(sl);
+        }
     }
 
     /**
      * asReadWriteLock.writeLock can be locked and unlocked
      */
-    public void testAsReadWriteLockWriteLock() {
+    public void testAsReadWriteLockWriteLock() throws Throwable {
         StampedLock sl = new StampedLock();
         Lock lock = sl.asReadWriteLock().writeLock();
-        lock.lock();
-        assertFalse(lock.tryLock());
-        lock.unlock();
-        assertTrue(lock.tryLock());
+        for (Action locker : lockLockers(lock)) {
+            locker.run();
+            assertTrue(sl.isWriteLocked());
+            assertFalse(sl.isReadLocked());
+            assertFalse(lock.tryLock());
+            lock.unlock();
+            assertUnlocked(sl);
+        }
     }
 
     /**
      * asReadWriteLock.readLock can be locked and unlocked
      */
-    public void testAsReadWriteLockReadLock() {
+    public void testAsReadWriteLockReadLock() throws Throwable {
         StampedLock sl = new StampedLock();
         Lock lock = sl.asReadWriteLock().readLock();
-        lock.lock();
-        lock.unlock();
-        assertTrue(lock.tryLock());
+        for (Action locker : lockLockers(lock)) {
+            locker.run();
+            assertTrue(sl.isReadLocked());
+            assertFalse(sl.isWriteLocked());
+            assertEquals(1, sl.getReadLockCount());
+            locker.run();
+            assertTrue(sl.isReadLocked());
+            assertEquals(2, sl.getReadLockCount());
+            lock.unlock();
+            lock.unlock();
+            assertUnlocked(sl);
+        }
     }
 
     /**
@@ -985,8 +1004,7 @@
         Runnable[] actions = {
             () -> {
                 StampedLock sl = new StampedLock();
-                long stamp = sl.tryOptimisticRead();
-                assertTrue(stamp != 0);
+                long stamp = assertValid(sl, sl.tryOptimisticRead());
                 sl.unlockRead(stamp);
             },
             () -> {
@@ -1003,21 +1021,21 @@
             },
             () -> {
                 StampedLock sl = new StampedLock();
-                long stamp = sl.tryOptimisticRead();
                 sl.readLock();
+                long stamp = assertValid(sl, sl.tryOptimisticRead());
                 sl.unlockRead(stamp);
             },
             () -> {
                 StampedLock sl = new StampedLock();
-                long stamp = sl.tryOptimisticRead();
                 sl.readLock();
+                long stamp = assertValid(sl, sl.tryOptimisticRead());
                 sl.unlock(stamp);
             },
 
             () -> {
                 StampedLock sl = new StampedLock();
                 long stamp = sl.tryConvertToOptimisticRead(sl.writeLock());
-                assertTrue(stamp != 0);
+                assertValid(sl, stamp);
                 sl.writeLock();
                 sl.unlockWrite(stamp);
             },
@@ -1043,7 +1061,7 @@
             () -> {
                 StampedLock sl = new StampedLock();
                 long stamp = sl.tryConvertToOptimisticRead(sl.readLock());
-                assertTrue(stamp != 0);
+                assertValid(sl, stamp);
                 sl.writeLock();
                 sl.unlockWrite(stamp);
             },
@@ -1063,7 +1081,7 @@
                 StampedLock sl = new StampedLock();
                 sl.readLock();
                 long stamp = sl.tryConvertToOptimisticRead(sl.readLock());
-                assertTrue(stamp != 0);
+                assertValid(sl, stamp);
                 sl.readLock();
                 sl.unlockRead(stamp);
             },
@@ -1106,100 +1124,84 @@
     }
 
     /**
-     * Invalid write stamps result in IllegalMonitorStateException
+     * Invalid stamps result in IllegalMonitorStateException
      */
-    public void testInvalidWriteStampsThrowIllegalMonitorStateException() {
-        List<Function<StampedLock, Long>> writeLockers = new ArrayList<>();
-        writeLockers.add((sl) -> sl.writeLock());
-        writeLockers.add((sl) -> writeLockInterruptiblyUninterrupted(sl));
-        writeLockers.add((sl) -> tryWriteLockUninterrupted(sl, Long.MIN_VALUE, DAYS));
-        writeLockers.add((sl) -> tryWriteLockUninterrupted(sl, 0, DAYS));
+    public void testInvalidStampsThrowIllegalMonitorStateException() {
+        final StampedLock sl = new StampedLock();
+
+        assertThrows(IllegalMonitorStateException.class,
+                     () -> sl.unlockWrite(0L),
+                     () -> sl.unlockRead(0L),
+                     () -> sl.unlock(0L));
 
-        List<BiConsumer<StampedLock, Long>> writeUnlockers = new ArrayList<>();
-        writeUnlockers.add((sl, stamp) -> sl.unlockWrite(stamp));
-        writeUnlockers.add((sl, stamp) -> assertTrue(sl.tryUnlockWrite()));
-        writeUnlockers.add((sl, stamp) -> sl.asWriteLock().unlock());
-        writeUnlockers.add((sl, stamp) -> sl.unlock(stamp));
+        final long optimisticStamp = sl.tryOptimisticRead();
+        final long readStamp = sl.readLock();
+        sl.unlockRead(readStamp);
+        final long writeStamp = sl.writeLock();
+        sl.unlockWrite(writeStamp);
+        assertTrue(optimisticStamp != 0L && readStamp != 0L && writeStamp != 0L);
+        final long[] noLongerValidStamps = { optimisticStamp, readStamp, writeStamp };
+        final Runnable assertNoLongerValidStampsThrow = () -> {
+            for (long noLongerValidStamp : noLongerValidStamps)
+                assertThrows(IllegalMonitorStateException.class,
+                             () -> sl.unlockWrite(noLongerValidStamp),
+                             () -> sl.unlockRead(noLongerValidStamp),
+                             () -> sl.unlock(noLongerValidStamp));
+        };
+        assertNoLongerValidStampsThrow.run();
 
-        List<Consumer<StampedLock>> mutaters = new ArrayList<>();
-        mutaters.add((sl) -> {});
-        mutaters.add((sl) -> sl.readLock());
-        for (Function<StampedLock, Long> writeLocker : writeLockers)
-            mutaters.add((sl) -> writeLocker.apply(sl));
+        for (Function<StampedLock, Long> readLocker : readLockers())
+        for (BiConsumer<StampedLock, Long> readUnlocker : readUnlockers()) {
+            final long stamp = readLocker.apply(sl);
+            assertValid(sl, stamp);
+            assertNoLongerValidStampsThrow.run();
+            assertThrows(IllegalMonitorStateException.class,
+                         () -> sl.unlockWrite(stamp),
+                         () -> sl.unlockRead(sl.tryOptimisticRead()),
+                         () -> sl.unlockRead(0L));
+            readUnlocker.accept(sl, stamp);
+            assertUnlocked(sl);
+            assertNoLongerValidStampsThrow.run();
+        }
 
-        for (Function<StampedLock, Long> writeLocker : writeLockers)
-        for (BiConsumer<StampedLock, Long> writeUnlocker : writeUnlockers)
-        for (Consumer<StampedLock> mutater : mutaters) {
-            final StampedLock sl = new StampedLock();
+        for (Function<StampedLock, Long> writeLocker : writeLockers())
+        for (BiConsumer<StampedLock, Long> writeUnlocker : writeUnlockers()) {
             final long stamp = writeLocker.apply(sl);
-            assertTrue(stamp != 0L);
+            assertValid(sl, stamp);
+            assertNoLongerValidStampsThrow.run();
             assertThrows(IllegalMonitorStateException.class,
-                         () -> sl.unlockRead(stamp));
+                         () -> sl.unlockRead(stamp),
+                         () -> sl.unlockWrite(0L));
             writeUnlocker.accept(sl, stamp);
-            mutater.accept(sl);
-            assertThrows(IllegalMonitorStateException.class,
-                         () -> sl.unlock(stamp),
-                         () -> sl.unlockRead(stamp),
-                         () -> sl.unlockWrite(stamp));
+            assertUnlocked(sl);
+            assertNoLongerValidStampsThrow.run();
         }
     }
 
     /**
-     * Invalid read stamps result in IllegalMonitorStateException
+     * Read locks can be very deeply nested
      */
-    public void testInvalidReadStampsThrowIllegalMonitorStateException() {
-        List<Function<StampedLock, Long>> readLockers = new ArrayList<>();
-        readLockers.add((sl) -> sl.readLock());
-        readLockers.add((sl) -> readLockInterruptiblyUninterrupted(sl));
-        readLockers.add((sl) -> tryReadLockUninterrupted(sl, Long.MIN_VALUE, DAYS));
-        readLockers.add((sl) -> tryReadLockUninterrupted(sl, 0, DAYS));
-
-        List<BiConsumer<StampedLock, Long>> readUnlockers = new ArrayList<>();
-        readUnlockers.add((sl, stamp) -> sl.unlockRead(stamp));
-        readUnlockers.add((sl, stamp) -> assertTrue(sl.tryUnlockRead()));
-        readUnlockers.add((sl, stamp) -> sl.asReadLock().unlock());
-        readUnlockers.add((sl, stamp) -> sl.unlock(stamp));
-
-        List<Function<StampedLock, Long>> writeLockers = new ArrayList<>();
-        writeLockers.add((sl) -> sl.writeLock());
-        writeLockers.add((sl) -> writeLockInterruptiblyUninterrupted(sl));
-        writeLockers.add((sl) -> tryWriteLockUninterrupted(sl, Long.MIN_VALUE, DAYS));
-        writeLockers.add((sl) -> tryWriteLockUninterrupted(sl, 0, DAYS));
-
-        List<BiConsumer<StampedLock, Long>> writeUnlockers = new ArrayList<>();
-        writeUnlockers.add((sl, stamp) -> sl.unlockWrite(stamp));
-        writeUnlockers.add((sl, stamp) -> assertTrue(sl.tryUnlockWrite()));
-        writeUnlockers.add((sl, stamp) -> sl.asWriteLock().unlock());
-        writeUnlockers.add((sl, stamp) -> sl.unlock(stamp));
-
-
-        for (Function<StampedLock, Long> readLocker : readLockers)
-        for (BiConsumer<StampedLock, Long> readUnlocker : readUnlockers)
-        for (Function<StampedLock, Long> writeLocker : writeLockers)
-        for (BiConsumer<StampedLock, Long> writeUnlocker : writeUnlockers) {
-            final StampedLock sl = new StampedLock();
-            final long stamp = readLocker.apply(sl);
-            assertTrue(stamp != 0L);
-            assertThrows(IllegalMonitorStateException.class,
-                         () -> sl.unlockWrite(stamp));
-            readUnlocker.accept(sl, stamp);
-            assertThrows(IllegalMonitorStateException.class,
-                         () -> sl.unlock(stamp),
-                         () -> sl.unlockRead(stamp),
-                         () -> sl.unlockWrite(stamp));
-            final long writeStamp = writeLocker.apply(sl);
-            assertTrue(writeStamp != 0L);
-            assertTrue(writeStamp != stamp);
-            assertThrows(IllegalMonitorStateException.class,
-                         () -> sl.unlock(stamp),
-                         () -> sl.unlockRead(stamp),
-                         () -> sl.unlockWrite(stamp));
-            writeUnlocker.accept(sl, writeStamp);
-            assertThrows(IllegalMonitorStateException.class,
-                         () -> sl.unlock(stamp),
-                         () -> sl.unlockRead(stamp),
-                         () -> sl.unlockWrite(stamp));
+    public void testDeeplyNestedReadLocks() {
+        final StampedLock lock = new StampedLock();
+        final int depth = 300;
+        final long[] stamps = new long[depth];
+        final List<Function<StampedLock, Long>> readLockers = readLockers();
+        final List<BiConsumer<StampedLock, Long>> readUnlockers = readUnlockers();
+        for (int i = 0; i < depth; i++) {
+            Function<StampedLock, Long> readLocker
+                = readLockers.get(i % readLockers.size());
+            long stamp = readLocker.apply(lock);
+            assertEquals(i + 1, lock.getReadLockCount());
+            assertTrue(lock.isReadLocked());
+            stamps[i] = stamp;
         }
+        for (int i = 0; i < depth; i++) {
+            BiConsumer<StampedLock, Long> readUnlocker
+                = readUnlockers.get(i % readUnlockers.size());
+            assertEquals(depth - i, lock.getReadLockCount());
+            assertTrue(lock.isReadLocked());
+            readUnlocker.accept(lock, stamps[depth - 1 - i]);
+        }
+        assertUnlocked(lock);
     }
-
 }
--- a/jdk/test/java/util/logging/modules/GetResourceBundleTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/java/util/logging/modules/GetResourceBundleTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -66,10 +66,10 @@
         for (String mn : modules) {
             Path msrc = MOD_SRC_DIR.resolve(mn);
             assertTrue(CompilerUtils.compile(msrc, MOD_DEST_DIR,
-                    "-modulesourcepath", MOD_SRC_DIR.toString()));
+                    "--module-source-path", MOD_SRC_DIR.toString()));
         }
         assertTrue(CompilerUtils.compile(PKG_SRC_DIR, PKG_DEST_DIR,
-                "-modulepath", MOD_DEST_DIR.toString(), "-addmods", String.join(",", modules)));
+                "--module-path", MOD_DEST_DIR.toString(), "--add-modules", String.join(",", modules)));
 
         // copy resource files
         String[] files = { "m1/p1/resource/p.properties", "m2/p2/resource/p.properties" };
@@ -84,8 +84,8 @@
     public void runWithoutSecurityManager() throws Exception {
         int exitValue = executeTestJava(
                 "-cp", PKG_DEST_DIR.toString(),
-                "-mp", MOD_DEST_DIR.toString(),
-                "-addmods", String.join(",", modules),
+                "--module-path", MOD_DEST_DIR.toString(),
+                "--add-modules", String.join(",", modules),
                 "p3.test.ResourceBundleTest")
                 .outputTo(System.out)
                 .errorTo(System.err)
@@ -98,8 +98,8 @@
         int exitValue = executeTestJava(
                 "-Djava.security.manager",
                 "-cp", PKG_DEST_DIR.toString(),
-                "-mp", MOD_DEST_DIR.toString(),
-                "-addmods", String.join(",", modules),
+                "--module-path", MOD_DEST_DIR.toString(),
+                "--add-modules", String.join(",", modules),
                 "p3.test.ResourceBundleTest")
                 .outputTo(System.out)
                 .errorTo(System.err)
--- a/jdk/test/javax/crypto/Cipher/CipherStreamClose.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/javax/crypto/Cipher/CipherStreamClose.java	Wed Jul 05 22:05:22 2017 +0200
@@ -27,8 +27,8 @@
  * @summary Make sure Cipher IO streams doesn't call extra doFinal if close()
  * is called multiple times.  Additionally, verify the input and output streams
  * match with encryption and decryption with non-stream crypto.
- * @compile -addmods java.xml.bind CipherStreamClose.java
- * @run main/othervm -addmods java.xml.bind CipherStreamClose
+ * @modules java.xml.bind
+ * @run main CipherStreamClose
  */
 
 import java.io.*;
--- a/jdk/test/javax/imageio/plugins/external_plugin_tests/TestClassPathPlugin.sh	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/javax/imageio/plugins/external_plugin_tests/TestClassPathPlugin.sh	Wed Jul 05 22:05:22 2017 +0200
@@ -86,7 +86,7 @@
 
 # expect to find SimpReader on module path
 echo "Test modular jar .. "
-$JAVA -mp $PLUGINDIR -cp $TESTDIR simptest.TestSIMPPlugin
+$JAVA --module-path $PLUGINDIR -cp $TESTDIR simptest.TestSIMPPlugin
 
 if [ $? -ne 0 ]; then
     exception=1
@@ -94,7 +94,7 @@
 fi
 
 echo "Test modular jar with security manager .."
-$JAVA -Djava.security.manager -mp $PLUGINDIR -cp $TESTDIR simptest.TestSIMPPlugin
+$JAVA -Djava.security.manager --module-path $PLUGINDIR -cp $TESTDIR simptest.TestSIMPPlugin
 if [ $? -ne 0 ]; then
     exception=1
     echo "modular jar with security manager test failed: exception thrown!"
--- a/jdk/test/javax/imageio/stream/StreamCloserLeak/run_test.sh	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/javax/imageio/stream/StreamCloserLeak/run_test.sh	Wed Jul 05 22:05:22 2017 +0200
@@ -199,14 +199,14 @@
 fi
 
 # Verify that all classloaders are destroyed
-${TESTJAVA}/bin/java -XaddExports:java.desktop/sun.awt=ALL-UNNAMED ${TESTVMOPTS} -cp Test.jar test.Main
+${TESTJAVA}/bin/java --add-exports java.desktop/sun.awt=ALL-UNNAMED ${TESTVMOPTS} -cp Test.jar test.Main
 if [ $? -ne 0 ] ; then
     fail "Test FAILED: some classloaders weren't destroyed."
 fi
 
 
 # Verify that ImageIO shutdown hook works correcly
-${TESTJAVA}/bin/java -XaddExports:java.desktop/sun.awt=ALL-UNNAMED ${TESTVMOPTS} \
+${TESTJAVA}/bin/java --add-exports java.desktop/sun.awt=ALL-UNNAMED ${TESTVMOPTS} \
     -cp Test.jar -DforgetSomeStreams=true test.Main
 if [ $? -ne 0 ] ; then
     fail "Test FAILED: some classloaders weren't destroyed of shutdown hook failed."
--- a/jdk/test/javax/naming/module/basic.sh	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/javax/naming/module/basic.sh	Wed Jul 05 22:05:22 2017 +0200
@@ -78,27 +78,27 @@
 
 echo "\nPreparing the 'test' module..."
 mkdir -p mods/test
-$JAVAC -d mods -modulesourcepath $TESTSRC/src `find $TESTSRC/src/test -name "*.java"`
+$JAVAC -d mods --module-source-path $TESTSRC/src `find $TESTSRC/src/test -name "*.java"`
 
 
 echo "\nRunning with the 'java.desktop' module..."
-$JAVA -Dtest.src=${TESTSRC} -mp mods -m test/test.StoreObject ldap://localhost/dc=ie,dc=oracle,dc=com
+$JAVA -Dtest.src=${TESTSRC} -p mods -m test/test.StoreObject ldap://localhost/dc=ie,dc=oracle,dc=com
 
 echo "\nRunning with the 'person' module..."
-$JAVA -Dtest.src=${TESTSRC} -mp mods -m test/test.StorePerson ldap://localhost/dc=ie,dc=oracle,dc=com
+$JAVA -Dtest.src=${TESTSRC} -p mods -m test/test.StorePerson ldap://localhost/dc=ie,dc=oracle,dc=com
 
 echo "\nRunning with the 'fruit' module..."
-$JAVA -Dtest.src=${TESTSRC} -mp mods -m test/test.StoreFruit ldap://localhost/dc=ie,dc=oracle,dc=com
+$JAVA -Dtest.src=${TESTSRC} -p mods -m test/test.StoreFruit ldap://localhost/dc=ie,dc=oracle,dc=com
 
 echo "\nRunning with the 'hello' module..."
-$JAVA -Dtest.src=${TESTSRC} -mp mods -m test/test.StoreRemote ldap://localhost/dc=ie,dc=oracle,dc=com
+$JAVA -Dtest.src=${TESTSRC} -p mods -m test/test.StoreRemote ldap://localhost/dc=ie,dc=oracle,dc=com
 
 echo "\nRunning with the 'foo' module..."
-$JAVA -Dtest.src=${TESTSRC} -mp mods -m test/test.ConnectWithFoo ldap://localhost/dc=ie,dc=oracle,dc=com
+$JAVA -Dtest.src=${TESTSRC} -p mods -m test/test.ConnectWithFoo ldap://localhost/dc=ie,dc=oracle,dc=com
 
 echo "\nRunning with the 'authz' module..."
-$JAVA -Dtest.src=${TESTSRC} -mp mods -m test/test.ConnectWithAuthzId ldap://localhost/dc=ie,dc=oracle,dc=com
+$JAVA -Dtest.src=${TESTSRC} -p mods -m test/test.ConnectWithAuthzId ldap://localhost/dc=ie,dc=oracle,dc=com
 
 echo "\nRunning with the 'ldapv4' module..."
-$JAVA -Dtest.src=${TESTSRC} -mp mods -m test/test.ReadByUrl ldap://localhost/dc=ie,dc=oracle,dc=com
+$JAVA -Dtest.src=${TESTSRC} -p mods -m test/test.ReadByUrl ldap://localhost/dc=ie,dc=oracle,dc=com
 
--- a/jdk/test/javax/rmi/PortableRemoteObject/8146975/RmiIiopReturnValueTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/javax/rmi/PortableRemoteObject/8146975/RmiIiopReturnValueTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -25,18 +25,19 @@
  * @test
  * @bug 8146975
  * @summary test RMI-IIOP with value object return
+ * @modules java.corba
  * @library /lib/testlibrary
  * @build jdk.testlibrary.*
- * @compile -addmods java.corba Test.java Test3.java Test4.java
+ * @compile Test.java Test3.java Test4.java
  *    HelloInterface.java HelloServer.java
  *    HelloClient.java HelloImpl.java _HelloImpl_Tie.java _HelloInterface_Stub.java
  *    RmiIiopReturnValueTest.java
- * @run main/othervm -addmods java.corba
+ * @run main/othervm
  *    -Djava.naming.provider.url=iiop://localhost:5050
  *    -Djava.naming.factory.initial=com.sun.jndi.cosnaming.CNCtxFactory
  *    RmiIiopReturnValueTest -port 5049
  * @run main/othervm/secure=java.lang.SecurityManager/policy=jtreg.test.policy
- *    -addmods java.corba -Djava.naming.provider.url=iiop://localhost:5050
+ *    -Djava.naming.provider.url=iiop://localhost:5050
  *    -Djava.naming.factory.initial=com.sun.jndi.cosnaming.CNCtxFactory
  *    RmiIiopReturnValueTest -port 5049
  */
@@ -102,12 +103,12 @@
 
     static void startRmiIiopServer() throws Exception {
         System.out.println("\nStarting RmiIiopServer");
-        // java -addmods java.corba -cp .
+        // java --add-modules java.corba -cp .
         // -Djava.naming.factory.initial=com.sun.jndi.cosnaming.CNCtxFactory
         // -Djava.naming.provider.url=iiop://localhost:5050 HelloServer -port 5049
         List<String> commands = new ArrayList<>();
         commands.add(RmiIiopReturnValueTest.JAVA);
-        commands.add("-addmods");
+        commands.add("--add-modules");
         commands.add("java.corba");
         commands.add("-Djava.naming.factory.initial=com.sun.jndi.cosnaming.CNCtxFactory");
         commands.add("-Djava.naming.provider.url=iiop://localhost:5050");
--- a/jdk/test/javax/rmi/PortableRemoteObject/ConcurrentHashMapTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/javax/rmi/PortableRemoteObject/ConcurrentHashMapTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -28,12 +28,12 @@
  * @library /lib/testlibrary
  * @modules java.corba
  * @build jdk.testlibrary.*
- * @compile -addmods java.corba Test.java HelloInterface.java HelloServer.java HelloClient.java
+ * @compile Test.java HelloInterface.java HelloServer.java HelloClient.java
  *    HelloImpl.java _HelloImpl_Tie.java _HelloInterface_Stub.java ConcurrentHashMapTest.java
- * @run main/othervm -addmods java.corba -Djava.naming.provider.url=iiop://localhost:1050
+ * @run main/othervm -Djava.naming.provider.url=iiop://localhost:1050
  *    -Djava.naming.factory.initial=com.sun.jndi.cosnaming.CNCtxFactory ConcurrentHashMapTest
  * @run main/othervm/secure=java.lang.SecurityManager/policy=jtreg.test.policy
- *    -addmods java.corba -Djava.naming.provider.url=iiop://localhost:1050
+ *    -Djava.naming.provider.url=iiop://localhost:1050
  *    -Djava.naming.factory.initial=com.sun.jndi.cosnaming.CNCtxFactory ConcurrentHashMapTest
  * @key intermittent
  */
@@ -98,12 +98,12 @@
 
     static void startRmiIiopServer() throws Exception {
         System.out.println("\nStarting RmiServer");
-        // java -cp . -addmods java.corba
+        // java -cp . --add-modules java.corba
         // -Djava.naming.factory.initial=com.sun.jndi.cosnaming.CNCtxFactory
         // -Djava.naming.provider.url=iiop://localhost:1050 HelloServer
         List<String> commands = new ArrayList<>();
         commands.add(ConcurrentHashMapTest.JAVA);
-        commands.add("-addmods");
+        commands.add("--add-modules");
         commands.add("java.corba");
         commands.add("-Djava.naming.factory.initial=com.sun.jndi.cosnaming.CNCtxFactory");
         commands.add("-Djava.naming.provider.url=iiop://localhost:1050");
--- a/jdk/test/javax/security/auth/login/modules/JaasModularClientTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/javax/security/auth/login/modules/JaasModularClientTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -291,7 +291,7 @@
         vmArgs.put("-Djava.security.auth.login.config=", SRC.resolve(
                 "jaas.conf").toFile().getCanonicalPath());
         if (addModName != null && sModuletype == MODULE_TYPE.AUTO) {
-            vmArgs.put("-addmods ", addModName);
+            vmArgs.put("--add-modules ", addModName);
         }
         return vmArgs;
     }
--- a/jdk/test/javax/security/auth/login/modules/JaasModularDefaultHandlerTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/javax/security/auth/login/modules/JaasModularDefaultHandlerTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -247,7 +247,7 @@
         if (addModName != null
                 && !(cModuleType == MODULE_TYPE.EXPLICIT
                 && sModuletype == MODULE_TYPE.EXPLICIT)) {
-            vmArgs.put("-addmods ", addModName);
+            vmArgs.put("--add-modules=", addModName);
         }
         return vmArgs;
     }
--- a/jdk/test/javax/smartcardio/CommandAPDUTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/javax/smartcardio/CommandAPDUTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -26,8 +26,8 @@
  * @bug 8049021
  * @summary Test different constructors for CommandAPDU and check CLA,INS,NC,NE,
  * P1,and P2
- * @compile -addmods java.smartcardio CommandAPDUTest.java
- * @run testng/othervm -addmods java.smartcardio CommandAPDUTest
+ * @compile --add-modules=java.smartcardio CommandAPDUTest.java
+ * @run testng/othervm --add-modules=java.smartcardio CommandAPDUTest
  */
 import java.nio.ByteBuffer;
 import javax.smartcardio.CommandAPDU;
--- a/jdk/test/javax/smartcardio/HistoricalBytes.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/javax/smartcardio/HistoricalBytes.java	Wed Jul 05 22:05:22 2017 +0200
@@ -26,8 +26,8 @@
  * @bug 6445367
  * @summary Verify that ATR.getHistoricalBytes() works
  * @author Andreas Sterbenz
- * @compile -addmods java.smartcardio HistoricalBytes.java
- * @run main/othervm -addmods java.smartcardio HistoricalBytes
+ * @compile --add-modules=java.smartcardio HistoricalBytes.java
+ * @run main/othervm --add-modules=java.smartcardio HistoricalBytes
  */
 
 import java.util.Arrays;
--- a/jdk/test/javax/smartcardio/ResponseAPDUTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/javax/smartcardio/ResponseAPDUTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -25,8 +25,8 @@
  * @test
  * @bug 8049021
  * @summary Construct ResponseAPDU from byte array and check NR< SW, SW1 and SW2
- * @compile -addmods java.smartcardio ResponseAPDUTest.java
- * @run testng/othervm -addmods java.smartcardio ResponseAPDUTest
+ * @compile --add-modules=java.smartcardio ResponseAPDUTest.java
+ * @run testng/othervm --add-modules=java.smartcardio ResponseAPDUTest
  */
 import javax.smartcardio.ResponseAPDU;
 import static org.testng.Assert.*;
--- a/jdk/test/javax/smartcardio/Serialize.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/javax/smartcardio/Serialize.java	Wed Jul 05 22:05:22 2017 +0200
@@ -26,8 +26,8 @@
  * @bug 6445367
  * @summary make sure serialization works
  * @author Andreas Sterbenz
- * @compile -addmods java.smartcardio Serialize.java
- * @run main/othervm -addmods java.smartcardio Serialize
+ * @compile --add-modules=java.smartcardio Serialize.java
+ * @run main/othervm --add-modules=java.smartcardio Serialize
  */
 
 import java.io.*;
--- a/jdk/test/javax/smartcardio/TerminalFactorySpiTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/javax/smartcardio/TerminalFactorySpiTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -25,8 +25,8 @@
  * @test
  * @bug 8049021
  * @summary Test if we can write new provider for smart card
- * @compile -addmods java.smartcardio TerminalFactorySpiTest.java
- * @run main/othervm/java.security.policy=policy -addmods java.smartcardio TerminalFactorySpiTest
+ * @compile --add-modules=java.smartcardio TerminalFactorySpiTest.java
+ * @run main/othervm/java.security.policy=policy --add-modules=java.smartcardio TerminalFactorySpiTest
  */
 import java.security.Provider;
 import java.security.Security;
--- a/jdk/test/javax/smartcardio/TestCardPermission.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/javax/smartcardio/TestCardPermission.java	Wed Jul 05 22:05:22 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -23,11 +23,11 @@
 
 /**
  * @test
- * @bug 6293767
+ * @bug 6293767 6469513
  * @summary Test for the CardPermission class
  * @author Andreas Sterbenz
- * @compile -addmods java.smartcardio TestCardPermission.java
- * @run main/othervm -addmods java.smartcardio TestCardPermission
+ * @compile --add-modules=java.smartcardio TestCardPermission.java
+ * @run main/othervm --add-modules=java.smartcardio TestCardPermission
  */
 
 import javax.smartcardio.*;
@@ -49,15 +49,14 @@
         test("Reset,coNnect", "connect,reset");
         test("exclusive,*,connect", "*");
         test("connect,reset,exclusive,transmitControl,getBasicChannel,openLogicalChannel", "*");
+        test(null, null);
 
-        invalid(null);
         invalid("");
         invalid("foo");
         invalid("connect, reset");
         invalid("connect,,reset");
         invalid("connect,");
         invalid(",connect");
-        invalid("");
     }
 
     private static void invalid(String s) throws Exception {
@@ -77,7 +76,7 @@
         CardPermission p = new CardPermission("*", actions);
         System.out.println(p);
         String a = p.getActions();
-        if (canon.equals(a) == false) {
+        if (canon != null && canon.equals(a) == false) {
             throw new Exception("Canonical actions mismatch: " + canon + " != " + a);
         }
     }
--- a/jdk/test/javax/smartcardio/TestCommandAPDU.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/javax/smartcardio/TestCommandAPDU.java	Wed Jul 05 22:05:22 2017 +0200
@@ -27,8 +27,8 @@
  * @summary Test for the CommandAPDU class
  * @author Andreas Sterbenz
  * @key randomness
- * @compile -addmods java.smartcardio TestCommandAPDU.java
- * @run main/othervm -addmods java.smartcardio TestCommandAPDU
+ * @compile --add-modules=java.smartcardio TestCommandAPDU.java
+ * @run main/othervm --add-modules=java.smartcardio TestCommandAPDU
  */
 
 import java.util.*;
--- a/jdk/test/javax/transaction/testng/Driver.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/javax/transaction/testng/Driver.java	Wed Jul 05 22:05:22 2017 +0200
@@ -24,14 +24,14 @@
 /**
  * @test
  * @modules java.sql java.transaction
- * @compile -addmods java.transaction
+ * @compile
  *   test/transaction/InvalidTransactionExceptionTests.java
  *   test/transaction/TransactionRequiredExceptionTests.java
  *   test/transaction/TransactionRolledbackExceptionTests.java
  *   test/transaction/XAExceptionTests.java
  *   util/SerializedTransactionExceptions.java
- * @run testng/othervm -addmods java.transaction test.transaction.InvalidTransactionExceptionTests
- * @run testng/othervm -addmods java.transaction test.transaction.TransactionRequiredExceptionTests
- * @run testng/othervm -addmods java.transaction test.transaction.TransactionRolledbackExceptionTests
- * @run testng/othervm -addmods java.transaction util.SerializedTransactionExceptions
+ * @run testng/othervm test.transaction.InvalidTransactionExceptionTests
+ * @run testng/othervm test.transaction.TransactionRequiredExceptionTests
+ * @run testng/othervm test.transaction.TransactionRolledbackExceptionTests
+ * @run testng/othervm util.SerializedTransactionExceptions
  */
--- a/jdk/test/javax/xml/bind/JAXBContext/JAXBContextWithAbstractFactory.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/javax/xml/bind/JAXBContext/JAXBContextWithAbstractFactory.java	Wed Jul 05 22:05:22 2017 +0200
@@ -33,8 +33,8 @@
  * @bug 8150173
  * @summary Verifies that a factory which inherit its createContext method
  *          from an abstract subclass of JAXBContextFactory can be instantiated.
- * @compile -addmods java.xml.bind JAXBContextWithAbstractFactory.java
- * @run main/othervm -addmods java.xml.bind JAXBContextWithAbstractFactory
+ * @modules java.xml.bind
+ * @run main/othervm JAXBContextWithAbstractFactory
  */
 public class JAXBContextWithAbstractFactory {
     private static JAXBContext tmp;
--- a/jdk/test/javax/xml/bind/JAXBContext/JAXBContextWithLegacyFactory.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/javax/xml/bind/JAXBContext/JAXBContextWithLegacyFactory.java	Wed Jul 05 22:05:22 2017 +0200
@@ -35,8 +35,8 @@
  * @bug 8150173
  * @summary Verifies that a JAXBContext can be created with a legacy
  *          factory class that has static createContext methods.
- * @compile -addmods java.xml.bind JAXBContextWithLegacyFactory.java
- * @run main/othervm -addmods java.xml.bind JAXBContextWithLegacyFactory
+ * @modules java.xml.bind
+ * @run main/othervm JAXBContextWithLegacyFactory
  */
 public class JAXBContextWithLegacyFactory {
     private static JAXBContext tmp;
--- a/jdk/test/javax/xml/bind/JAXBContext/JAXBContextWithSubclassedFactory.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/javax/xml/bind/JAXBContext/JAXBContextWithSubclassedFactory.java	Wed Jul 05 22:05:22 2017 +0200
@@ -36,8 +36,8 @@
  * @bug 8150173
  * @summary Verifies that a factory which inherit its createContext method
  *          from a concrete subclass of JAXBContextFactory is be instantiated.
- * @compile -addmods java.xml.bind JAXBContextWithSubclassedFactory.java
- * @run main/othervm -addmods java.xml.bind JAXBContextWithSubclassedFactory
+ * @modules java.xml.bind
+ * @run main/othervm JAXBContextWithSubclassedFactory
  */
 public class JAXBContextWithSubclassedFactory {
     static JAXBContext tmp;
--- a/jdk/test/javax/xml/bind/jxc/8073872/SchemagenStackOverflow.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/javax/xml/bind/jxc/8073872/SchemagenStackOverflow.java	Wed Jul 05 22:05:22 2017 +0200
@@ -26,9 +26,8 @@
  * @bug 8073872
  * @summary test that stackoverflow is not observable when element
  *          references containing class
- * @modules java.xml
  * @modules java.xml.bind
- * @compile Foo.java
+ * @compile SchemagenStackOverflow.java Foo.java
  * @run testng/othervm SchemagenStackOverflow
  */
 
--- a/jdk/test/javax/xml/bind/marshal/8134111/UnmarshalTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/javax/xml/bind/marshal/8134111/UnmarshalTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -26,9 +26,10 @@
  * @bug 8134111
  * @summary test that elements without namespace is ignored by unmarshaller
  *          when elementFormDefault is set to QUALIFIED.
- * @compile testTypes/package-info.java testTypes/Root.java
+ * @modules java.xml.bind
+ * @compile UnmarshalTest.java
+ *          testTypes/package-info.java testTypes/Root.java
  *          testTypes/WhenType.java testTypes/ObjectFactory.java
- * @modules java.xml.bind
  * @run testng/othervm UnmarshalTest
  */
 
--- a/jdk/test/javax/xml/bind/xjc/8032884/XjcOptionalPropertyTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/javax/xml/bind/xjc/8032884/XjcOptionalPropertyTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -100,7 +100,7 @@
     // Compile java classes with javac tool
     void compileXjcGeneratedClasses() throws Exception {
         JDKToolLauncher javacLauncher = JDKToolLauncher.createUsingTestJDK("javac");
-        javacLauncher.addToolArg("-addmods");
+        javacLauncher.addToolArg("--add-modules");
         javacLauncher.addToolArg("java.xml.bind");
         javacLauncher.addToolArg(xjcResultDir.resolve("Foo.java").toString());
         System.out.println("Compiling xjc generated class: " + Arrays.asList(javacLauncher.getCommand()));
--- a/jdk/test/javax/xml/bind/xjc/8145039/JaxbMarshallTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/javax/xml/bind/xjc/8145039/JaxbMarshallTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -127,7 +127,7 @@
     // Compile java classes with javac tool
     void compileXjcGeneratedClasses() throws Exception {
         JDKToolLauncher javacLauncher = JDKToolLauncher.createUsingTestJDK("javac");
-        javacLauncher.addToolArg("-addmods");
+        javacLauncher.addToolArg("--add-modules");
         javacLauncher.addToolArg("java.xml.bind");
         javacLauncher.addToolArg(xjcResultDir.resolve("ObjectFactory.java").toString());
         javacLauncher.addToolArg(xjcResultDir.resolve("TypesLongList.java").toString());
--- a/jdk/test/javax/xml/jaxp/common/8035437/run.sh	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/javax/xml/jaxp/common/8035437/run.sh	Wed Jul 05 22:05:22 2017 +0200
@@ -34,12 +34,12 @@
    -d compile/java.xml -Xmodule:java.xml $TESTSRC/Document.java $TESTSRC/Node.java || exit 1
 
 $COMPILEJAVA/bin/javac ${TESTJAVACOPTS} ${TESTTOOLVMOPTS} \
-   -d exec/java.xml -Xpatch:java.xml=compile/java.xml -Xmodule:java.xml $TESTSRC/DocumentImpl.java || exit 2
+   -d exec/java.xml --patch-module java.xml=compile/java.xml -Xmodule:java.xml $TESTSRC/DocumentImpl.java || exit 2
 
 $COMPILEJAVA/bin/javac ${TESTJAVACOPTS} ${TESTTOOLVMOPTS} \
    $TESTSRC/AbstractMethodErrorTest.java -d exec || exit 3
 
-$TESTJAVA/bin/java ${TESTVMOPTS} -Xpatch:java.xml=exec -cp exec AbstractMethodErrorTest || exit 4
+$TESTJAVA/bin/java ${TESTVMOPTS} --patch-module java.xml=exec -cp exec AbstractMethodErrorTest || exit 4
 
 exit 0
 
--- a/jdk/test/javax/xml/soap/XmlTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/javax/xml/soap/XmlTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -38,8 +38,8 @@
 
 /*
  * @test
- * @compile -addmods java.xml.ws XmlTest.java
- * @run main/othervm -addmods java.xml.ws XmlTest
+ * @modules java.xml.ws
+ * @run main XmlTest
  * @summary tests JAF DataHandler can be instantiated; test serialize and
  *   deserialize SOAP message containing xml attachment
  */
--- a/jdk/test/javax/xml/soap/spi/SAAJFactoryTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/javax/xml/soap/spi/SAAJFactoryTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -50,28 +50,28 @@
  *      scenario14 javax.xml.soap.MessageFactory=saaj.factory.Valid saaj.factory.Valid2 -
  *
  * @modules java.xml.ws
- * @compile -addmods java.xml.ws saaj/factory/Invalid.java saaj/factory/Valid.java
+ * @compile saaj/factory/Invalid.java saaj/factory/Valid.java
  *     saaj/factory/Valid2.java saaj/factory/Valid3.java SAAJFactoryTest.java
  *
- * @run main/othervm -addmods java.xml.ws
+ * @run main/othervm
  *      SAAJFactoryTest com.sun.xml.internal.messaging.saaj.soap.ver1_1.SOAPMessageFactory1_1Impl - scenario2 - -
- * @run main/othervm -addmods java.xml.ws -Djavax.xml.soap.MessageFactory=saaj.factory.Valid
+ * @run main/othervm -Djavax.xml.soap.MessageFactory=saaj.factory.Valid
  *      SAAJFactoryTest saaj.factory.Valid - scenario5 - -
- * @run main/othervm -addmods java.xml.ws -Djavax.xml.soap.MessageFactory=saaj.factory.NonExisting
+ * @run main/othervm -Djavax.xml.soap.MessageFactory=saaj.factory.NonExisting
  *      SAAJFactoryTest - javax.xml.soap.SOAPException scenario6 - -
- * @run main/othervm -addmods java.xml.ws -Djavax.xml.soap.MessageFactory=saaj.factory.Invalid
+ * @run main/othervm -Djavax.xml.soap.MessageFactory=saaj.factory.Invalid
  *      SAAJFactoryTest - javax.xml.soap.SOAPException scenario7 - -
- * @run main/othervm  -addmods java.xml.ws
+ * @run main/othervm
  *      SAAJFactoryTest saaj.factory.Valid - scenario8 - saaj.factory.Valid
- * @run main/othervm -addmods java.xml.ws
+ * @run main/othervm
  *      SAAJFactoryTest saaj.factory.Valid - scenario9 - saaj.factory.Valid
- * @run main/othervm -addmods java.xml.ws
+ * @run main/othervm
  *      SAAJFactoryTest - javax.xml.soap.SOAPException scenario10 - saaj.factory.NonExisting
- * @run main/othervm -addmods java.xml.ws
+ * @run main/othervm
  *      SAAJFactoryTest - javax.xml.soap.SOAPException scenario11 - saaj.factory.Invalid scenario11 - saaj.factory.Invalid
- * @run main/othervm  -addmods java.xml.ws
+ * @run main/othervm
  *      SAAJFactoryTest com.sun.xml.internal.messaging.saaj.soap.ver1_1.SOAPMessageFactory1_1Impl - scenario12 - -
- * @run main/othervm -addmods java.xml.ws
+ * @run main/othervm
  *      SAAJFactoryTest saaj.factory.Valid - scenario15 - saaj.factory.Valid
  */
 public class SAAJFactoryTest {
@@ -207,4 +207,3 @@
     }
 
 }
-
--- a/jdk/test/javax/xml/ws/8043129/MailTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/javax/xml/ws/8043129/MailTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -28,8 +28,7 @@
  * @author mkos
  * @library javax.mail.jar
  * @modules java.xml.ws
- * @compile -addmods java.xml.ws MailTest.java
- * @run main/othervm -addmods java.xml.ws MailTest
+ * @run main MailTest
  */
 
 import javax.activation.CommandMap;
--- a/jdk/test/javax/xml/ws/clientjar/TestWsImport.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/javax/xml/ws/clientjar/TestWsImport.java	Wed Jul 05 22:05:22 2017 +0200
@@ -25,8 +25,8 @@
  * @test
  * @bug 8016271 8026405
  * @summary wsimport -clientjar does not create portable jar on windows due to hardcoded '\'
- * @compile -addmods java.xml.ws TestWsImport.java
- * @run main/othervm -addmods java.xml.ws TestWsImport
+ * @modules java.xml.ws
+ * @run main TestWsImport
  */
 
 import javax.xml.namespace.QName;
--- a/jdk/test/javax/xml/ws/publish/WSTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/javax/xml/ws/publish/WSTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -26,8 +26,7 @@
  * @bug 8146086
  * @summary Publishing two webservices on same port fails with "java.net.BindException: Address already in use"
  * @modules java.xml.ws
- * @compile -addmods java.xml.ws WSTest.java
- * @run main/othervm -addmods java.xml.ws WSTest
+ * @run main/othervm WSTest
  */
 import javax.jws.WebMethod;
 import javax.jws.WebService;
--- a/jdk/test/javax/xml/ws/xsanymixed/Test.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/javax/xml/ws/xsanymixed/Test.java	Wed Jul 05 22:05:22 2017 +0200
@@ -28,8 +28,7 @@
  *          no white space changes and no changes to namespace prefixes
  * @modules java.xml.ws
  * @run shell compile-wsdl.sh
- * @compile -addmods java.xml.ws Test.java
- * @run main/othervm -addmods java.xml.ws Test
+ * @run main/othervm Test
  */
 
 import com.sun.net.httpserver.HttpServer;
--- a/jdk/test/jdk/internal/misc/VM/RuntimeArguments.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/jdk/internal/misc/VM/RuntimeArguments.java	Wed Jul 05 22:05:22 2017 +0200
@@ -26,6 +26,8 @@
  * @summary Basic test of VM::getRuntimeArguments
  * @library /lib/testlibrary
  * @modules java.base/jdk.internal.misc
+ *          java.compact3
+ *          jdk.zipfs
  * @run testng RuntimeArguments
  */
 
@@ -45,21 +47,28 @@
     public Object[][] options() {
         return new Object[][] {
             { // CLI options
-              List.of("-XaddExports:java.base/jdk.internal.misc=ALL-UNNAMED",
-                      "-XaddExports:java.base/jdk.internal.perf=ALL-UNNAMED",
-                      "-addmods", "jdk.zipfs"),
+              List.of("--add-exports",
+                      "java.base/jdk.internal.misc=ALL-UNNAMED",
+                      "--add-exports",
+                      "java.base/jdk.internal.perf=ALL-UNNAMED",
+                      "--add-modules",
+                      "jdk.zipfs"),
               // expected runtime arguments
-              List.of("-Djdk.launcher.addexports.0=java.base/jdk.internal.misc=ALL-UNNAMED",
-                      "-Djdk.launcher.addexports.1=java.base/jdk.internal.perf=ALL-UNNAMED",
-                      "-Djdk.launcher.addmods=jdk.zipfs")
+              List.of("--add-exports=java.base/jdk.internal.misc=ALL-UNNAMED",
+                      "--add-exports=java.base/jdk.internal.perf=ALL-UNNAMED",
+                      "--add-modules=jdk.zipfs")
             },
             { // CLI options
-              List.of("-XaddExports:java.base/jdk.internal.misc=ALL-UNNAMED",
-                      "-addmods", "jdk.zipfs",
-                      "-limitmods", "java.compact3"),
+              List.of("--add-exports",
+                      "java.base/jdk.internal.misc=ALL-UNNAMED",
+                      "--add-modules",
+                      "jdk.zipfs",
+                      "--limit-modules",
+                      "java.compact3"),
               // expected runtime arguments
-              List.of("-Djdk.launcher.addexports.0=java.base/jdk.internal.misc=ALL-UNNAMED",
-                      "-Djdk.launcher.addmods=jdk.zipfs", "-Djdk.launcher.limitmods=java.compact3")
+              List.of("--add-exports=java.base/jdk.internal.misc=ALL-UNNAMED",
+                      "--add-modules=jdk.zipfs",
+                      "--limit-modules=java.compact3"),
             },
         };
     };
--- a/jdk/test/jdk/internal/reflect/Reflection/GetCallerClassTest.sh	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/jdk/internal/reflect/Reflection/GetCallerClassTest.sh	Wed Jul 05 22:05:22 2017 +0200
@@ -55,7 +55,7 @@
 rm -rf ${BCP}
 mkdir ${BCP}
 
-EXTRAOPTS="-XaddExports:java.base/jdk.internal.reflect=ALL-UNNAMED"
+EXTRAOPTS="--add-exports java.base/jdk.internal.reflect=ALL-UNNAMED"
 
 # Compile GetCallerClass in bootclasspath
 ${COMPILEJAVA}/bin/javac ${TESTTOOLVMOPTS} ${EXTRAOPTS} \
--- a/jdk/test/jdk/modules/etc/VerifyModuleDelegation.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/jdk/modules/etc/VerifyModuleDelegation.java	Wed Jul 05 22:05:22 2017 +0200
@@ -26,7 +26,7 @@
  * @summary Verify the defining class loader of each module never delegates
  *          to its child class loader. Also sanity check java.compact2
  *          requires.
- * @run testng/othervm -Djdk.launcher.addmods=ALL-SYSTEM VerifyModuleDelegation
+ * @run testng/othervm --add-modules=ALL-SYSTEM VerifyModuleDelegation
  */
 
 import java.lang.module.ModuleDescriptor;
@@ -51,11 +51,11 @@
 
     private static final ModuleDescriptor COMPACT2
         = new ModuleDescriptor.Builder(JAVA_COMPACT2)
-            .requires(MANDATED, JAVA_BASE)
-            .requires(PUBLIC, JAVA_COMPACT1)
-            .requires(PUBLIC, "java.rmi")
-            .requires(PUBLIC, "java.sql")
-            .requires(PUBLIC, "java.xml")
+            .requires(Set.of(MANDATED), JAVA_BASE)
+            .requires(Set.of(PUBLIC), JAVA_COMPACT1)
+            .requires(Set.of(PUBLIC), "java.rmi")
+            .requires(Set.of(PUBLIC), "java.sql")
+            .requires(Set.of(PUBLIC), "java.xml")
             .build();
 
     private static final Set<ModuleReference> MREFS
--- a/jdk/test/jdk/modules/scenarios/automaticmodules/RunWithAutomaticModules.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/jdk/modules/scenarios/automaticmodules/RunWithAutomaticModules.java	Wed Jul 05 22:05:22 2017 +0200
@@ -100,15 +100,15 @@
         compiled = CompilerUtils
             .compile(SRC_DIR.resolve(testModule),
                     MODS_DIR.resolve(testModule),
-                    "-mp", MODS_DIR.toString());
+                    "--module-path", MODS_DIR.toString());
         assertTrue(compiled);
 
 
-        // launch the test. Need -addmods because nothing explicitly depends on logging
+        // launch the test. Need --add-mdoules because nothing explicitly depends on logging
 
         int exitValue
-            = executeTestJava("-mp", MODS_DIR.toString(),
-                              "-addmods", "logging",
+            = executeTestJava("--module-path", MODS_DIR.toString(),
+                              "--add-modules", "logging",
                               "-m", testModule + "/" + mainClass)
                 .outputTo(System.out)
                 .errorTo(System.out)
@@ -159,7 +159,7 @@
         compiled = CompilerUtils
                 .compile(SRC_DIR.resolve(testModule),
                         MODS_DIR.resolve(testModule),
-                        "-mp", MODS_DIR.toString());
+                        "--module-path", MODS_DIR.toString());
 
         assertTrue(compiled);
 
@@ -167,7 +167,7 @@
         // launch the test
 
         int exitValue
-            = executeTestJava("-mp", MODS_DIR.toString(),
+            = executeTestJava("--module-path", MODS_DIR.toString(),
                               "-m", testModule + "/" + mainClass)
                 .outputTo(System.out)
                 .errorTo(System.out)
--- a/jdk/test/jdk/modules/scenarios/container/ContainerTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/jdk/modules/scenarios/container/ContainerTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -98,7 +98,7 @@
 
         compiled = CompilerUtils.compile(SRC_DIR.resolve("app1"),
                                          dir.resolve("app1"),
-                                         "-upgrademodulepath", dir.toString());
+                                         "--upgrade-module-path", dir.toString());
         assertTrue(compiled);
     }
 
@@ -116,7 +116,7 @@
 
         compiled = CompilerUtils.compile(SRC_DIR.resolve("app2"),
                                          dir.resolve("app2"),
-                                         "-mp", dir.toString());
+                                         "--module-path", dir.toString());
         assertTrue(compiled);
     }
 
@@ -134,7 +134,7 @@
     public void testContainer() throws Exception {
 
         int exitValue
-            = executeTestJava("-mp", MLIB_DIR.toString(),
+            = executeTestJava("--module-path", MLIB_DIR.toString(),
                               "-m", CONTAINER_MODULE)
                 .outputTo(System.out)
                 .errorTo(System.err)
--- a/jdk/test/jdk/modules/scenarios/overlappingpackages/OverlappingPackagesTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/jdk/modules/scenarios/overlappingpackages/OverlappingPackagesTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -74,7 +74,7 @@
      */
     public void testNoOverlappingPackages() throws Exception {
         int exitValue
-            = executeTestJava("-mp", MODS_DIR.toString(),
+            = executeTestJava("--module-path", MODS_DIR.toString(),
                               "-m", "test/test.Main")
                 .outputTo(System.out)
                 .errorTo(System.err)
@@ -85,13 +85,13 @@
 
 
     /**
-     * Run the test with "-addmods misc", the misc module has package
+     * Run the test with "--add-modules misc", the misc module has package
      * jdk.internal.misc and so should overlap with the base module.
      */
     public void testOverlapWithBaseModule() throws Exception {
         int exitValue
-            = executeTestJava("-mp", MODS_DIR.toString(),
-                              "-addmods", "misc",
+            = executeTestJava("--module-path", MODS_DIR.toString(),
+                              "-add-modules", "misc",
                               "-m", "test/test.Main")
                 .outputTo(System.out)
                 .errorTo(System.err)
@@ -101,12 +101,12 @@
     }
 
     /**
-     * Run the test with "-addmods m1,m2". Both modules have package p.
+     * Run the test with "--add-modules m1,m2". Both modules have package p.
      */
     public void testOverlap() throws Exception {
         int exitValue
-            = executeTestJava("-mp", MODS_DIR.toString(),
-                              "-addmods", "m1,m2",
+            = executeTestJava("--module-path", MODS_DIR.toString(),
+                              "--add-modules", "m1,m2",
                               "-m", "test/test.Main")
                 .outputTo(System.out)
                 .errorTo(System.err)
--- a/jdk/test/sun/awt/shell/ShellFolderMemoryLeak.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/sun/awt/shell/ShellFolderMemoryLeak.java	Wed Jul 05 22:05:22 2017 +0200
@@ -93,7 +93,7 @@
         String command = javaPath + File.separator + "bin" + File.separator
                 + "java -Xmx256M" + arg1 + " -cp "
                 + classPathDir
-                + " -XaddExports:java.desktop/sun.awt.shell=ALL-UNNAMED"
+                + " --add-exports=java.desktop/sun.awt.shell=ALL-UNNAMED"
                 + " ShellFolderMemoryLeak " + arg2;
         process = Runtime.getRuntime().exec(command);
         BufferedReader input = null;
--- a/jdk/test/sun/management/jmxremote/bootstrap/CustomLauncherTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/sun/management/jmxremote/bootstrap/CustomLauncherTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -150,7 +150,7 @@
             ProcessBuilder client = ProcessTools.createJavaProcessBuilder(
                 "-cp",
                 TEST_CLASSPATH,
-                "-XaddExports:java.management/sun.management=ALL-UNNAMED",
+                "--add-exports", "java.management/sun.management=ALL-UNNAMED",
                 "TestManager",
                 String.valueOf(serverPrc.getPid()),
                 port.get(),
--- a/jdk/test/sun/management/jmxremote/bootstrap/LocalManagementTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/sun/management/jmxremote/bootstrap/LocalManagementTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -131,7 +131,7 @@
             ProcessBuilder client = ProcessTools.createJavaProcessBuilder(
                 "-cp",
                 TEST_CLASSPATH,
-                "-XaddExports:java.management/sun.management=ALL-UNNAMED",
+                "--add-exports", "java.management/sun.management=ALL-UNNAMED",
                 "TestManager",
                 String.valueOf(serverPrc.getPid()),
                 port.get(),
--- a/jdk/test/sun/management/jmxremote/bootstrap/RmiBootstrapTest.sh	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/sun/management/jmxremote/bootstrap/RmiBootstrapTest.sh	Wed Jul 05 22:05:22 2017 +0200
@@ -51,8 +51,8 @@
 DEBUGOPTIONS=""
 export DEBUGOPTIONS
 
-EXTRAOPTIONS="-XaddExports:java.management/sun.management=ALL-UNNAMED \
- -XaddExports:java.management/sun.management.jmxremote=ALL-UNNAMED"
+EXTRAOPTIONS="--add-exports java.management/sun.management=ALL-UNNAMED \
+ --add-exports java.management/sun.management.jmxremote=ALL-UNNAMED"
 export EXTRAOPTIONS
 
 # Call the common generic test
--- a/jdk/test/sun/management/jmxremote/bootstrap/RmiSslBootstrapTest.sh	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/sun/management/jmxremote/bootstrap/RmiSslBootstrapTest.sh	Wed Jul 05 22:05:22 2017 +0200
@@ -49,8 +49,8 @@
 DEBUGOPTIONS=""
 export DEBUGOPTIONS
 
-EXTRAOPTIONS="-XaddExports:java.management/sun.management=ALL-UNNAMED \
- -XaddExports:java.management/sun.management.jmxremote=ALL-UNNAMED"
+EXTRAOPTIONS="--add-exports java.management/sun.management=ALL-UNNAMED \
+ --add-exports java.management/sun.management.jmxremote=ALL-UNNAMED"
 export EXTRAOPTIONS
 
 # Call the common generic test
--- a/jdk/test/sun/management/jmxremote/bootstrap/RmiSslNoKeyStoreTest.sh	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/sun/management/jmxremote/bootstrap/RmiSslNoKeyStoreTest.sh	Wed Jul 05 22:05:22 2017 +0200
@@ -48,8 +48,8 @@
 DEBUGOPTIONS=""
 export DEBUGOPTIONS
 
-EXTRAOPTIONS="-XaddExports:java.management/sun.management=ALL-UNNAMED \
- -XaddExports:java.management/sun.management.jmxremote=ALL-UNNAMED"
+EXTRAOPTIONS="--add-exports java.management/sun.management=ALL-UNNAMED \
+ --add-exports java.management/sun.management.jmxremote=ALL-UNNAMED"
 export EXTRAOPTIONS
 
 # Call the common generic test
--- a/jdk/test/sun/net/www/protocol/https/HttpsURLConnection/PostThruProxy.sh	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/sun/net/www/protocol/https/HttpsURLConnection/PostThruProxy.sh	Wed Jul 05 22:05:22 2017 +0200
@@ -51,7 +51,7 @@
     ;;
 esac
 
-EXTRAOPTS="-XaddExports:java.base/sun.net.www=ALL-UNNAMED"
+EXTRAOPTS="--add-exports java.base/sun.net.www=ALL-UNNAMED"
 
 ${COMPILEJAVA}${FS}bin${FS}javac ${TESTJAVACOPTS} ${TESTTOOLVMOPTS} ${EXTRAOPTS} -d . \
     ${TESTSRC}${FS}OriginServer.java \
--- a/jdk/test/sun/net/www/protocol/https/HttpsURLConnection/PostThruProxyWithAuth.sh	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/sun/net/www/protocol/https/HttpsURLConnection/PostThruProxyWithAuth.sh	Wed Jul 05 22:05:22 2017 +0200
@@ -51,7 +51,7 @@
     ;;
 esac
 
-EXTRAOPTS="-XaddExports:java.base/sun.net.www=ALL-UNNAMED"
+EXTRAOPTS="--add-exports java.base/sun.net.www=ALL-UNNAMED"
 ${COMPILEJAVA}${FS}bin${FS}javac ${TESTJAVACOPTS} ${TESTTOOLVMOPTS} ${EXTRAOPTS} \
     -d . ${TESTSRC}${FS}OriginServer.java \
     ${TESTSRC}${FS}ProxyTunnelServer.java \
--- a/jdk/test/sun/net/www/protocol/jrt/OtherResources.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/sun/net/www/protocol/jrt/OtherResources.java	Wed Jul 05 22:05:22 2017 +0200
@@ -36,7 +36,7 @@
         // check that java.desktop is not in the set of readable modules
         try {
             Class.forName("java.awt.Component");
-            throw new RuntimeException("Need to run with -limitmods java.base");
+            throw new RuntimeException("Need to run with --limit-modules java.base");
         } catch (ClassNotFoundException expected) { }
 
         // access resource in the java.desktop module
--- a/jdk/test/sun/net/www/protocol/jrt/other_resources.sh	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/sun/net/www/protocol/jrt/other_resources.sh	Wed Jul 05 22:05:22 2017 +0200
@@ -26,7 +26,7 @@
 # @run shell other_resources.sh
 # @summary Access a jrt:/ resource in an observable module that is not in
 #  the boot layer and hence not known to the built-in class loaders. This
-#  test is a shell test because the run tag doesn't support -limitmods.
+#  test is a shell test because the run tag doesn't support --limit-modules.
 
 set -e
 
@@ -39,7 +39,7 @@
 fi
 
 JAVA="$TESTJAVA/bin/java ${TESTVMOPTS}"
-$JAVA -limitmods java.base -cp $TESTCLASSES OtherResources
+$JAVA --limit-modules java.base -cp $TESTCLASSES OtherResources
 
 exit 0
 
--- a/jdk/test/sun/rmi/rmic/iiopCompilation/IIOPCompilation.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/sun/rmi/rmic/iiopCompilation/IIOPCompilation.java	Wed Jul 05 22:05:22 2017 +0200
@@ -30,8 +30,9 @@
  *          java.rmi/sun.rmi.transport
  *          java.rmi/sun.rmi.transport.tcp
  * @build TestLibrary
+ * @run main IIOPCompilation
+ *
  * @summary Compiles a PortableRemoteObject with rmic -iiop and ensures that stub and tie classes are generated.
- * @run main IIOPCompilation
  * @author Felix Yang
  *
  */
--- a/jdk/test/sun/rmi/runtime/Log/6409194/NoConsoleOutput.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/sun/rmi/runtime/Log/6409194/NoConsoleOutput.java	Wed Jul 05 22:05:22 2017 +0200
@@ -68,10 +68,10 @@
         // (neither on standard output, nor on standard err streams).
         JavaVM vm = new JavaVM(
                 DoRMIStuff.class.getName(),
-                "-XaddExports:java.rmi/sun.rmi.registry=ALL-UNNAMED"
-                + " -XaddExports:java.rmi/sun.rmi.server=ALL-UNNAMED"
-                + " -XaddExports:java.rmi/sun.rmi.transport=ALL-UNNAMED"
-                + " -XaddExports:java.rmi/sun.rmi.transport.tcp=ALL-UNNAMED"
+                "--add-exports=java.rmi/sun.rmi.registry=ALL-UNNAMED"
+                + " --add-exports=java.rmi/sun.rmi.server=ALL-UNNAMED"
+                + " --add-exports=java.rmi/sun.rmi.transport=ALL-UNNAMED"
+                + " --add-exports=java.rmi/sun.rmi.transport.tcp=ALL-UNNAMED"
                 + " -Djava.util.logging.config.file="
                 + loggingPropertiesFile, "", out, err);
         vm.execute();
--- a/jdk/test/sun/security/krb5/ccache/EmptyCC.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/sun/security/krb5/ccache/EmptyCC.java	Wed Jul 05 22:05:22 2017 +0200
@@ -27,7 +27,8 @@
  * @bug 8001208
  * @summary NPE in sun.security.krb5.Credentials.acquireDefaultCreds()
  * @library ../../../../java/security/testlibrary/
- * @modules java.security.jgss/sun.security.krb5
+ * @modules java.base/jdk.internal.misc
+ *          java.security.jgss/sun.security.krb5
  *          java.security.jgss/sun.security.krb5.internal.ccache
  * @compile -XDignore.symbol.file EmptyCC.java
  * @run main EmptyCC tmpcc
--- a/jdk/test/sun/security/krb5/tools/ktcheck.sh	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/sun/security/krb5/tools/ktcheck.sh	Wed Jul 05 22:05:22 2017 +0200
@@ -61,8 +61,8 @@
 EXTRA_OPTIONS="-Djava.security.krb5.conf=${TESTSRC}${FS}onlythree.conf"
 KTAB="${TESTJAVA}${FS}bin${FS}ktab -J${EXTRA_OPTIONS} -k $KEYTAB -f"
 CHECK="${TESTJAVA}${FS}bin${FS}java -cp ${TESTCLASSES} ${TESTVMOPTS} ${EXTRA_OPTIONS} \
-        -XaddExports:java.security.jgss/sun.security.krb5.internal.ktab=ALL-UNNAMED \
-        -XaddExports:java.security.jgss/sun.security.krb5=ALL-UNNAMED \
+        --add-exports java.security.jgss/sun.security.krb5.internal.ktab=ALL-UNNAMED \
+        --add-exports java.security.jgss/sun.security.krb5=ALL-UNNAMED \
         KtabCheck $KEYTAB"
 
 echo ${EXTRA_OPTIONS}
--- a/jdk/test/sun/security/mscapi/AccessKeyStore.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/sun/security/mscapi/AccessKeyStore.java	Wed Jul 05 22:05:22 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -22,7 +22,12 @@
  */
 
 /**
- * @see AccessKeyStore.sh
+ * @test
+ * @bug 6324295 6931562 8154113
+ * @modules jdk.crypto.mscapi
+ * @run main/othervm/java.security.policy==access.policy AccessKeyStore pass
+ * @run main/othervm/java.security.policy==noaccess.policy AccessKeyStore fail
+ * @summary Confirm that right permissions are granted to access keystores.
  */
 
 import java.security.Provider;
@@ -36,13 +41,16 @@
 
     public static void main(String[] args) throws Exception {
 
-        // Check that a security manager has been installed
+        // Check for security manager and required arg(s)
         if (System.getSecurityManager() == null) {
-            throw new Exception("A security manager has not been installed");
+            throw new Exception("Missing security manager");
         }
+        if (args.length <= 0) {
+            throw new Exception("Missing expected test status");
+        }
+        boolean shouldPass = args[0].equalsIgnoreCase("pass");
 
         Provider p = Security.getProvider("SunMSCAPI");
-
         System.out.println("SunMSCAPI provider classname is " +
             p.getClass().getName());
 
@@ -56,18 +64,14 @@
          *     SecurityPermission("authProvider.SunMSCAPI")
          */
         try {
-
             keyStore.load(null, null);
-
-            if (args.length > 0 && "-deny".equals(args[0])) {
+            if (!shouldPass) {
                 throw new Exception(
                     "Expected KeyStore.load to throw a SecurityException");
             }
-
         } catch (SecurityException se) {
-
-            if (args.length > 0 && "-deny".equals(args[0])) {
-                System.out.println("Caught the expected exception: " + se);
+            if (!shouldPass) {
+                System.out.println("Expected exception thrown: " + se);
                 return;
             } else {
                 throw se;
--- a/jdk/test/sun/security/mscapi/AccessKeyStore.sh	Mon Aug 15 08:28:26 2016 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,65 +0,0 @@
-#!/bin/sh
-
-#
-# Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved.
-# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-#
-# This code is free software; you can redistribute it and/or modify it
-# under the terms of the GNU General Public License version 2 only, as
-# published by the Free Software Foundation.
-#
-# This code is distributed in the hope that it will be useful, but WITHOUT
-# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
-# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
-# version 2 for more details (a copy is included in the LICENSE file that
-# accompanied this code).
-#
-# You should have received a copy of the GNU General Public License version
-# 2 along with this work; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
-#
-# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
-# or visit www.oracle.com if you need additional information or have any
-# questions.
-#
-
-
-# @test
-# @bug 6324295 6931562
-# @requires os.family == "windows"
-# @run shell AccessKeyStore.sh
-# @summary Confirm that permission must be granted to access keystores.
-
-OS=`uname -s`
-case "$OS" in
-    Windows* | CYGWIN* )
-
-    # 'uname -m' does not give us enough information -
-    #  should rely on $PROCESSOR_IDENTIFIER (as is done in Defs-windows.gmk),
-    #  but JTREG does not pass this env variable when executing a shell script.
-    #
-    #  execute test program - rely on it to exit if platform unsupported
-
-	${TESTJAVA}/bin/javac -d . ${TESTSRC}\\AccessKeyStore.java
-
-	echo "Using access.policy..."
-	${TESTJAVA}/bin/java ${TESTVMOPTS} \
-	    -Djava.security.manager \
-	    -Djava.security.policy==${TESTSRC}\\access.policy \
-	    AccessKeyStore
-
-	echo "Using noaccess.policy..."
-	${TESTJAVA}/bin/java ${TESTVMOPTS} \
-	    -Djava.security.manager \
-	    -Djava.security.policy==${TESTSRC}\\noaccess.policy \
-	    AccessKeyStore -deny
-
-	exit
-	;;
-
-    * )
-        echo "This test is not intended for '$OS' - passing test"
-        exit 0
-        ;;
-esac
-
--- a/jdk/test/sun/security/mscapi/PublicKeyInterop.sh	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/sun/security/mscapi/PublicKeyInterop.sh	Wed Jul 05 22:05:22 2017 +0200
@@ -62,9 +62,9 @@
 
         echo
         echo "Running the test..."
-        ${TESTJAVA}/bin/javac -XaddExports:java.base/sun.security.util=ALL-UNNAMED \
+        ${TESTJAVA}/bin/javac --add-exports java.base/sun.security.util=ALL-UNNAMED \
             ${TESTTOOLVMOPTS} ${TESTJAVACOPTS} -d . ${TESTSRC}\\PublicKeyInterop.java
-        ${TESTJAVA}/bin/java -XaddExports:java.base/sun.security.util=ALL-UNNAMED \
+        ${TESTJAVA}/bin/java --add-exports java.base/sun.security.util=ALL-UNNAMED \
             ${TESTVMOPTS} PublicKeyInterop
 
         rc=$?
--- a/jdk/test/sun/security/mscapi/ShortRSAKey1024.sh	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/sun/security/mscapi/ShortRSAKey1024.sh	Wed Jul 05 22:05:22 2017 +0200
@@ -88,10 +88,10 @@
 
         echo
         echo "Running the test..."
-        ${TESTJAVA}${FS}bin${FS}javac -XaddExports:java.base/sun.security.util=ALL-UNNAMED \
+        ${TESTJAVA}${FS}bin${FS}javac --add-exports java.base/sun.security.util=ALL-UNNAMED \
             ${TESTTOOLVMOPTS} ${TESTJAVACOPTS} -d . \
             ${TESTSRC}${FS}ShortRSAKeyWithinTLS.java
-        ${TESTJAVA}${FS}bin${FS}java -XaddExports:java.base/sun.security.util=ALL-UNNAMED \
+        ${TESTJAVA}${FS}bin${FS}java --add-exports java.base/sun.security.util=ALL-UNNAMED \
             ${TESTVMOPTS} ShortRSAKeyWithinTLS 7106773.$BITS $BITS \
             TLSv1.2 TLS_DHE_RSA_WITH_AES_128_CBC_SHA
 
--- a/jdk/test/sun/security/mscapi/access.policy	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/sun/security/mscapi/access.policy	Wed Jul 05 22:05:22 2017 +0200
@@ -1,19 +1,4 @@
 grant {
-    // These permissions are required for the test to start
-    permission java.lang.RuntimePermission 
-			"accessClassInPackage.sun.*";
-
-    permission java.lang.RuntimePermission "loadLibrary.*";
-
-    permission java.util.PropertyPermission "os.arch", "read";
-
-    permission java.util.PropertyPermission 
-			"sun.security.mscapi.keyStoreCompatibilityMode", "read";
-
-    permission java.io.FilePermission "<<ALL FILES>>", "read";
-
-    permission java.security.SecurityPermission "putProviderProperty.SunMSCAPI";
-
     // This permission is required for the test to run to completion
     permission java.security.SecurityPermission "authProvider.SunMSCAPI";
 };
--- a/jdk/test/sun/security/mscapi/noaccess.policy	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/sun/security/mscapi/noaccess.policy	Wed Jul 05 22:05:22 2017 +0200
@@ -1,19 +1,4 @@
 grant {
-    // These permissions are required for the test to start
-    permission java.lang.RuntimePermission 
-			"accessClassInPackage.sun.*";
-
-    permission java.lang.RuntimePermission "loadLibrary.*";
-
-    permission java.util.PropertyPermission "os.arch", "read";
-
-    permission java.util.PropertyPermission 
-			"sun.security.mscapi.keyStoreCompatibilityMode", "read";
-
-    permission java.io.FilePermission "<<ALL FILES>>", "read";
-
-    permission java.security.SecurityPermission "putProviderProperty.SunMSCAPI";
-
     // This permission is required for the test to run to completion
     //permission java.security.SecurityPermission "authProvider.SunMSCAPI";
 };
--- a/jdk/test/sun/security/provider/PolicyFile/Modules.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/sun/security/provider/PolicyFile/Modules.java	Wed Jul 05 22:05:22 2017 +0200
@@ -33,14 +33,14 @@
  *          java.sql
  *          java.xml
  *          java.xml.bind
+ *          java.xml.ws
  *          jdk.attach
  *          jdk.jdi
  *          jdk.net
  *          jdk.security.auth
  *          jdk.security.jgss
- * @compile -addmods java.xml.ws,java.smartcardio Modules.java
- * @run main/othervm/java.security.policy==modules.policy
- *     -addmods java.xml.ws,java.smartcardio Modules
+ * @compile --add-modules=java.xml.ws,java.smartcardio Modules.java
+ * @run main/othervm/java.security.policy==modules.policy Modules
  */
 
 import java.security.AccessController;
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/sun/security/ssl/SSLContextImpl/CustomizedCipherSuites.java	Wed Jul 05 22:05:22 2017 +0200
@@ -0,0 +1,270 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+// SunJSSE does not support dynamic system properties, no way to re-use
+// system properties in samevm/agentvm mode.
+
+/*
+ * @test
+ * @bug 8162362
+ * @summary Cannot enable previously default enabled cipher suites
+ * @run main/othervm
+ *      CustomizedCipherSuites Default true
+ *      TLS_RSA_WITH_AES_128_CBC_SHA
+ *      SSL_RSA_WITH_DES_CBC_SHA
+ * @run main/othervm
+ *      -Djdk.tls.client.cipherSuites="unknown"
+ *      CustomizedCipherSuites Default true
+ *      TLS_RSA_WITH_AES_128_CBC_SHA
+ *      SSL_RSA_WITH_DES_CBC_SHA
+ * @run main/othervm
+ *      -Djdk.tls.client.cipherSuites=""
+ *      CustomizedCipherSuites Default true
+ *      TLS_RSA_WITH_AES_128_CBC_SHA
+ *      SSL_RSA_WITH_DES_CBC_SHA
+ * @run main/othervm
+ *      -Djdk.tls.client.cipherSuites="SSL_RSA_WITH_DES_CBC_SHA"
+ *      CustomizedCipherSuites Default true
+ *      SSL_RSA_WITH_DES_CBC_SHA
+ *      TLS_RSA_WITH_AES_128_CBC_SHA
+ * @run main/othervm
+ *      -Djdk.tls.server.cipherSuites="SSL_RSA_WITH_DES_CBC_SHA"
+ *      CustomizedCipherSuites Default false
+ *      SSL_RSA_WITH_DES_CBC_SHA
+ *      TLS_RSA_WITH_AES_128_CBC_SHA
+ * @run main/othervm
+ *      -Djdk.tls.client.cipherSuites="TLS_RSA_WITH_AES_128_CBC_SHA,unknown,SSL_RSA_WITH_DES_CBC_SHA"
+ *      CustomizedCipherSuites Default true
+ *      SSL_RSA_WITH_DES_CBC_SHA
+ *      ""
+ * @run main/othervm
+ *      -Djdk.tls.server.cipherSuites="TLS_RSA_WITH_AES_128_CBC_SHA,unknown,SSL_RSA_WITH_DES_CBC_SHA"
+ *      CustomizedCipherSuites Default false
+ *      TLS_RSA_WITH_AES_128_CBC_SHA
+ *      ""
+ * @run main/othervm
+ *      -Djdk.tls.server.cipherSuites="SSL_RSA_WITH_DES_CBC_SHA"
+ *      CustomizedCipherSuites Default true
+ *      TLS_RSA_WITH_AES_128_CBC_SHA
+ *      SSL_RSA_WITH_DES_CBC_SHA
+ * @run main/othervm
+ *      -Djdk.tls.client.cipherSuites="SSL_RSA_WITH_DES_CBC_SHA"
+ *      CustomizedCipherSuites Default false
+ *      TLS_RSA_WITH_AES_128_CBC_SHA
+ *      SSL_RSA_WITH_DES_CBC_SHA
+ */
+
+import javax.net.ssl.*;
+
+/**
+ * Test the customized default cipher suites.
+ *
+ * This test is based on the behavior that SSL_RSA_WITH_DES_CBC_SHA is
+ * disabled by default, and TLS_RSA_WITH_AES_128_CBC_SHA is enabled by
+ * default in JDK.  If the behavior is changed in the future, please
+ * update the test cases above accordingly.
+ */
+public class CustomizedCipherSuites {
+
+    private static String contextProtocol;
+    private static boolean isClientMode;
+
+    private static String enabledCipherSuite;
+    private static String disabledCipherSuite;
+
+    public static void main(String[] args) throws Exception {
+
+        contextProtocol = trimQuotes(args[0]);
+        isClientMode = Boolean.parseBoolean(args[1]);
+        enabledCipherSuite = trimQuotes(args[2]);
+        disabledCipherSuite = trimQuotes(args[3]);
+
+        //
+        // Create instance of SSLContext with the specified protocol.
+        //
+        SSLContext context = SSLContext.getInstance(contextProtocol);
+
+        // Default SSLContext is initialized automatically.
+        if (!contextProtocol.equals("Default")) {
+            // Use default TK, KM and random.
+            context.init((KeyManager[])null, (TrustManager[])null, null);
+        }
+
+        // SSLContext default parameters is client mode in JDK.
+        if (isClientMode) {
+            //
+            // Check default parameters of the specified SSLContext protocol
+            //
+            SSLParameters parameters = context.getDefaultSSLParameters();
+            System.out.println("Checking SSLContext default parameters ...");
+            checkEnabledCiphers(parameters.getCipherSuites());
+        }
+
+        //
+        // Check supported parameters of the specified SSLContext protocol
+        //
+        SSLParameters parameters = context.getSupportedSSLParameters();
+        System.out.println("Checking SSLContext suppport parameters ...");
+        checkSupportedCiphers(parameters.getCipherSuites());
+
+
+        //
+        // Check the default cipher suites of SSLEngine.
+        //
+        SSLEngine engine = context.createSSLEngine();
+        engine.setUseClientMode(isClientMode);
+
+        System.out.println("Checking SSLEngine default cipher suites ...");
+        checkEnabledCiphers(engine.getEnabledCipherSuites());
+
+        //
+        // Check the supported cipher suites of SSLEngine.
+        //
+        System.out.println("Checking SSLEngine supported cipher suites ...");
+        checkSupportedCiphers(engine.getSupportedCipherSuites());
+
+        if (isClientMode) {
+            SSLSocketFactory factory = context.getSocketFactory();
+            // Use an unconnected socket.
+            try (SSLSocket socket = (SSLSocket)factory.createSocket()) {
+                //
+                // Check the default cipher suites of SSLSocket.
+                //
+                System.out.println(
+                        "Checking SSLSocket default cipher suites ...");
+                checkEnabledCiphers(socket.getEnabledCipherSuites());
+
+                //
+                // Check the supported cipher suites of SSLSocket.
+                //
+                System.out.println(
+                        "Checking SSLSocket supported cipher suites ...");
+                checkSupportedCiphers(socket.getSupportedCipherSuites());
+            }
+        } else {
+            SSLServerSocketFactory factory = context.getServerSocketFactory();
+            // Use an unbound server socket.
+            try (SSLServerSocket socket =
+                    (SSLServerSocket)factory.createServerSocket()) {
+                //
+                // Check the default cipher suites of SSLServerSocket.
+                //
+                System.out.println(
+                        "Checking SSLServerSocket default cipher suites ...");
+                checkEnabledCiphers(socket.getEnabledCipherSuites());
+
+                //
+                // Check the supported cipher suites of SSLServerSocket.
+                //
+                System.out.println(
+                        "Checking SSLServerSocket supported cipher suites ...");
+                checkSupportedCiphers(socket.getSupportedCipherSuites());
+            }
+        }
+
+        System.out.println("\t... Success");
+    }
+
+    private static void checkEnabledCiphers(
+            String[] ciphers) throws Exception {
+
+        if (ciphers.length == 0) {
+            throw new Exception("No default cipher suites");
+        }
+
+        boolean isMatch = false;
+        if (enabledCipherSuite.isEmpty()) {
+            // Don't check if not specify the expected cipher suite.
+            isMatch = true;
+        }
+
+        boolean isBroken = false;
+        for (String cipher : ciphers) {
+            System.out.println("\tdefault cipher suite " + cipher);
+            if (!enabledCipherSuite.isEmpty() &&
+                        cipher.equals(enabledCipherSuite)) {
+                isMatch = true;
+            }
+
+            if (!disabledCipherSuite.isEmpty() &&
+                        cipher.equals(disabledCipherSuite)) {
+                isBroken = true;
+            }
+        }
+
+        if (!isMatch) {
+            throw new Exception(
+                "Cipher suite " + enabledCipherSuite + " should be enabled");
+        }
+
+        if (isBroken) {
+            throw new Exception(
+                "Cipher suite " + disabledCipherSuite + " should be disabled");
+        }
+    }
+
+    private static void checkSupportedCiphers(
+            String[] ciphers) throws Exception {
+
+        if (ciphers.length == 0) {
+            throw new Exception("No supported cipher suites");
+        }
+
+        boolean hasEnabledCipherSuite = enabledCipherSuite.isEmpty();
+        boolean hasDisabledCipherSuite = disabledCipherSuite.isEmpty();
+        for (String cipher : ciphers) {
+            System.out.println("\tsupported cipher suite " + cipher);
+            if (!enabledCipherSuite.isEmpty() &&
+                        cipher.equals(enabledCipherSuite)) {
+                hasEnabledCipherSuite = true;
+            }
+
+            if (!disabledCipherSuite.isEmpty() &&
+                        cipher.equals(disabledCipherSuite)) {
+                hasDisabledCipherSuite = true;
+            }
+        }
+
+        if (!hasEnabledCipherSuite) {
+            throw new Exception(
+                "Cipher suite " + enabledCipherSuite + " should be supported");
+        }
+
+        if (!hasDisabledCipherSuite) {
+            throw new Exception(
+                "Cipher suite " + disabledCipherSuite + " should be supported");
+        }
+    }
+
+    private static String trimQuotes(String candidate) {
+        if (candidate != null && candidate.length() != 0) {
+            // Remove double quote marks from beginning/end of the string.
+            if (candidate.length() > 1 && candidate.charAt(0) == '"' &&
+                    candidate.charAt(candidate.length() - 1) == '"') {
+                return candidate.substring(1, candidate.length() - 1);
+            }
+        }
+
+        return candidate;
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/sun/security/ssl/StatusStapling/RunStatReqSelect.java	Wed Jul 05 22:05:22 2017 +0200
@@ -0,0 +1,33 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8132943
+ * @library ../../../../java/security/testlibrary
+ * @build CertificateBuilder SimpleOCSPServer
+ * @run main/othervm java.base/sun.security.ssl.StatusReqSelection
+ * @summary ServerHandshaker may select non-empty OCSPStatusRequest
+ *          structures when Responder ID selection is not supported
+ */
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/sun/security/ssl/StatusStapling/java.base/sun/security/ssl/StatusReqSelection.java	Wed Jul 05 22:05:22 2017 +0200
@@ -0,0 +1,899 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+// SunJSSE does not support dynamic system properties, no way to re-use
+// system properties in samevm/agentvm mode.
+
+// See ../../../../RunStatReqSelect.java for the jtreg header
+
+package sun.security.ssl;
+
+import javax.net.ssl.*;
+import javax.net.ssl.SSLEngineResult.*;
+import javax.security.auth.x500.X500Principal;
+import java.io.*;
+import java.math.BigInteger;
+import java.security.*;
+import java.nio.*;
+import java.security.cert.X509Certificate;
+import java.security.cert.Extension;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.concurrent.TimeUnit;
+
+import sun.security.provider.certpath.OCSPNonceExtension;
+import sun.security.provider.certpath.ResponderId;
+import sun.security.testlibrary.SimpleOCSPServer;
+import sun.security.testlibrary.CertificateBuilder;
+
+public class StatusReqSelection {
+
+    /*
+     * Enables logging of the SSLEngine operations.
+     */
+    private static final boolean logging = true;
+
+    /*
+     * Enables the JSSE system debugging system property:
+     *
+     *     -Djavax.net.debug=all
+     *
+     * This gives a lot of low-level information about operations underway,
+     * including specific handshake messages, and might be best examined
+     * after gaining some familiarity with this application.
+     */
+    private static final boolean debug = false;
+
+    // The following items are used to set up the keystores.
+    private static final String passwd = "passphrase";
+    private static final String ROOT_ALIAS = "root";
+    private static final String INT_ALIAS = "intermediate";
+    private static final String SSL_ALIAS = "ssl";
+
+    // PKI and server components we will need for this test
+    private static KeyManagerFactory kmf;
+    private static TrustManagerFactory tmf;
+    private static KeyStore rootKeystore;       // Root CA Keystore
+    private static KeyStore intKeystore;        // Intermediate CA Keystore
+    private static KeyStore serverKeystore;     // SSL Server Keystore
+    private static KeyStore trustStore;         // SSL Client trust store
+    private static SimpleOCSPServer rootOcsp;   // Root CA OCSP Responder
+    private static int rootOcspPort;            // Port for root OCSP
+    private static SimpleOCSPServer intOcsp;    // Intermediate CA OCSP server
+    private static int intOcspPort;             // Port for intermediate OCSP
+    private static SSLContext ctxStaple;        // SSLContext for all tests
+
+    // Some useful objects we will need for test purposes
+    private static final SecureRandom RNG = new SecureRandom();
+
+    // We'll be using these objects repeatedly to make hello messages
+    private static final ProtocolVersion VER_1_0 = ProtocolVersion.TLS10;
+    private static final ProtocolVersion VER_1_2 = ProtocolVersion.TLS12;
+    private static final CipherSuiteList SUITES = new CipherSuiteList(
+            CipherSuite.valueOf("TLS_RSA_WITH_AES_128_GCM_SHA256"));
+    private static final SessionId SID = new SessionId(new byte[0]);
+    private static final HelloExtension RNIEXT =
+            new RenegotiationInfoExtension(new byte[0], new byte[0]);
+    private static final List<SignatureAndHashAlgorithm> algList =
+            new ArrayList<SignatureAndHashAlgorithm>() {{
+               add(SignatureAndHashAlgorithm.valueOf(4, 1, 0));
+            }};         // List with only SHA256withRSA
+    private static final SignatureAlgorithmsExtension SIGALGEXT =
+            new SignatureAlgorithmsExtension(algList);
+
+    /*
+     * Main entry point for this test.
+     */
+    public static void main(String args[]) throws Exception {
+        int testsPassed = 0;
+
+        if (debug) {
+            System.setProperty("javax.net.debug", "ssl");
+        }
+
+        // All tests will have stapling enabled on the server side
+        System.setProperty("jdk.tls.server.enableStatusRequestExtension",
+                "true");
+
+        // Create a single SSLContext that we can use for all tests
+        ctxStaple = SSLContext.getInstance("TLS");
+
+        // Create the PKI we will use for the test and start the OCSP servers
+        createPKI();
+
+        // Set up the KeyManagerFactory and TrustManagerFactory
+        kmf = KeyManagerFactory.getInstance("PKIX");
+        kmf.init(serverKeystore, passwd.toCharArray());
+        tmf = TrustManagerFactory.getInstance("PKIX");
+        tmf.init(trustStore);
+
+        List<TestCase> testList = new ArrayList<TestCase>() {{
+            add(new TestCase("ClientHello: No stapling extensions",
+                    makeHelloNoStaplingExts(), false, false));
+            add(new TestCase("ClientHello: Default status_request only",
+                    makeDefaultStatReqOnly(), true, false));
+            add(new TestCase("ClientHello: Default status_request_v2 only",
+                    makeDefaultStatReqV2Only(), false, true));
+            add(new TestCase("ClientHello: Both status_request exts, default",
+                    makeDefaultStatReqBoth(), false, true));
+            add(new TestCase(
+                    "ClientHello: Hello with status_request and responder IDs",
+                    makeStatReqWithRid(), false, false));
+            add(new TestCase(
+                    "ClientHello: Hello with status_request using no " +
+                    "responder IDs but provides the OCSP nonce extension",
+                    makeStatReqNoRidNonce(), true, false));
+            add(new TestCase("ClientHello with default status_request and " +
+                    "status_request_v2 with ResponderIds",
+                    makeStatReqDefV2WithRid(), true, false));
+            add(new TestCase("ClientHello with default status_request and " +
+                    "status_request_v2 (OCSP_MULTI with ResponderId, " +
+                    "OCSP as a default request)",
+                    makeStatReqDefV2MultiWithRidSingleDef(), false, true));
+            add(new TestCase("ClientHello with status_request and " +
+                    "status_request_v2 and all OCSPStatusRequests use " +
+                    "Responder IDs",
+                    makeStatReqAllWithRid(), false, false));
+            add(new TestCase("ClientHello with default status_request and " +
+                    "status_request_v2 that has a default OCSP item and " +
+                    "multiple OCSP_MULTI items, only one is default",
+                    makeHelloMultiV2andSingle(), false, true));
+        }};
+
+        // Run the client and server property tests
+        for (TestCase test : testList) {
+            try {
+                log("*** Test: " + test.testName);
+                if (runTest(test)) {
+                    log("PASS: status_request: " + test.statReqEnabled +
+                            ", status_request_v2: " + test.statReqV2Enabled);
+                    testsPassed++;
+                }
+            } catch (Exception e) {
+                // If we get an exception, we'll count it as a failure
+                log("Test failure due to exception: " + e);
+            }
+            log("");
+        }
+
+        // Summary
+        if (testsPassed != testList.size()) {
+            throw new RuntimeException(testList.size() - testsPassed +
+                    " tests failed out of " + testList.size() + " total.");
+        } else {
+            log("Total tests: " + testList.size() + ", all passed");
+        }
+    }
+
+    private static boolean runTest(TestCase test) throws Exception {
+        SSLEngineResult serverResult;
+
+        // Create a Server SSLEngine to receive our customized ClientHello
+        ctxStaple.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
+        SSLEngine engine = ctxStaple.createSSLEngine();
+        engine.setUseClientMode(false);
+        engine.setNeedClientAuth(false);
+
+        SSLSession session = engine.getSession();
+        ByteBuffer serverOut = ByteBuffer.wrap("I'm a Server".getBytes());
+        ByteBuffer serverIn =
+                ByteBuffer.allocate(session.getApplicationBufferSize() + 50);
+        ByteBuffer sTOc =
+                ByteBuffer.allocateDirect(session.getPacketBufferSize());
+
+        // Send the ClientHello ByteBuffer in the test case
+        if (debug) {
+            System.out.println("Sending Client Hello:\n" +
+                    dumpHexBytes(test.data));
+        }
+
+        // Consume the client hello
+        serverResult = engine.unwrap(test.data, serverIn);
+        if (debug) {
+            log("server unwrap: ", serverResult);
+        }
+        if (serverResult.getStatus() != SSLEngineResult.Status.OK) {
+            throw new SSLException("Server unwrap got status: " +
+                    serverResult.getStatus());
+        } else if (serverResult.getHandshakeStatus() !=
+                SSLEngineResult.HandshakeStatus.NEED_TASK) {
+             throw new SSLException("Server unwrap expected NEED_TASK, got: " +
+                    serverResult.getHandshakeStatus());
+        }
+        runDelegatedTasks(serverResult, engine);
+        if (engine.getHandshakeStatus() !=
+                SSLEngineResult.HandshakeStatus.NEED_WRAP) {
+            throw new SSLException("Expected NEED_WRAP, got: " +
+                    engine.getHandshakeStatus());
+        }
+
+        // Generate a TLS record with the ServerHello
+        serverResult = engine.wrap(serverOut, sTOc);
+        if (debug) {
+            log("client wrap: ", serverResult);
+        }
+        if (serverResult.getStatus() != SSLEngineResult.Status.OK) {
+            throw new SSLException("Client wrap got status: " +
+                    serverResult.getStatus());
+        }
+        sTOc.flip();
+
+        if (debug) {
+            log("Server Response:\n" + dumpHexBytes(sTOc));
+        }
+
+        return checkServerHello(sTOc, test.statReqEnabled,
+                test.statReqV2Enabled);
+    }
+
+    /**
+     * Make a TLSv1.2 ClientHello with only RNI and no stapling extensions
+     */
+    private static ByteBuffer makeHelloNoStaplingExts() throws IOException {
+        // Craft the ClientHello byte buffer
+        HelloExtensions exts = new HelloExtensions();
+        exts.add(RNIEXT);
+        exts.add(SIGALGEXT);
+        return createTlsRecord(Record.ct_handshake, VER_1_2,
+                createClientHelloMsg(VER_1_2, SID, SUITES, exts));
+    }
+
+    /**
+     * Make a TLSv1.2 ClientHello with the RNI and Status Request extensions
+     */
+    private static ByteBuffer makeDefaultStatReqOnly() throws IOException {
+        // Craft the ClientHello byte buffer
+        HelloExtensions exts = new HelloExtensions();
+        exts.add(RNIEXT);
+        exts.add(SIGALGEXT);
+        exts.add(new CertStatusReqExtension(StatusRequestType.OCSP,
+                new OCSPStatusRequest(null, null)));
+        return createTlsRecord(Record.ct_handshake, VER_1_2,
+                createClientHelloMsg(VER_1_2, SID, SUITES, exts));
+    }
+
+    /**
+     * Make a TLSv1.2 ClientHello with the RNI and Status Request V2 extension
+     */
+    private static ByteBuffer makeDefaultStatReqV2Only() throws IOException {
+        // Craft the ClientHello byte buffer
+        HelloExtensions exts = new HelloExtensions();
+        OCSPStatusRequest osr = new OCSPStatusRequest();
+        List<CertStatusReqItemV2> itemList = new ArrayList<>(2);
+        itemList.add(new CertStatusReqItemV2(StatusRequestType.OCSP_MULTI,
+                osr));
+        itemList.add(new CertStatusReqItemV2(StatusRequestType.OCSP, osr));
+
+        exts.add(RNIEXT);
+        exts.add(SIGALGEXT);
+        exts.add(new CertStatusReqListV2Extension(itemList));
+        return createTlsRecord(Record.ct_handshake, VER_1_2,
+                createClientHelloMsg(VER_1_2, SID, SUITES, exts));
+    }
+    /**
+     * Make a TLSv1.2 ClientHello with Status Request and Status Request V2
+     * extensions.
+     */
+    private static ByteBuffer makeDefaultStatReqBoth() throws IOException {
+        // Craft the ClientHello byte buffer
+        HelloExtensions exts = new HelloExtensions();
+        OCSPStatusRequest osr = new OCSPStatusRequest();
+        List<CertStatusReqItemV2> itemList = new ArrayList<>(2);
+        itemList.add(new CertStatusReqItemV2(StatusRequestType.OCSP_MULTI,
+                osr));
+        itemList.add(new CertStatusReqItemV2(StatusRequestType.OCSP, osr));
+
+        exts.add(RNIEXT);
+        exts.add(SIGALGEXT);
+        exts.add(new CertStatusReqExtension(StatusRequestType.OCSP,
+                new OCSPStatusRequest(null, null)));
+        exts.add(new CertStatusReqListV2Extension(itemList));
+        return createTlsRecord(Record.ct_handshake, VER_1_2,
+                createClientHelloMsg(VER_1_2, SID, SUITES, exts));
+    }
+
+    /**
+     * Make a ClientHello using a status_request that has a single
+     * responder ID in it.
+     */
+    private static ByteBuffer makeStatReqWithRid() throws IOException {
+        HelloExtensions exts = new HelloExtensions();
+        exts.add(RNIEXT);
+        exts.add(SIGALGEXT);
+        List<ResponderId> rids = new ArrayList<ResponderId>() {{
+            add(new ResponderId(new X500Principal("CN=Foo")));
+        }};
+        exts.add(new CertStatusReqExtension(StatusRequestType.OCSP,
+                new OCSPStatusRequest(rids, null)));
+        return createTlsRecord(Record.ct_handshake, VER_1_2,
+                createClientHelloMsg(VER_1_2, SID, SUITES, exts));
+    }
+
+    /**
+     * Make a ClientHello using a status_request that has no
+     * responder IDs but does provide the nonce extension.
+     */
+    private static ByteBuffer makeStatReqNoRidNonce() throws IOException {
+        HelloExtensions exts = new HelloExtensions();
+        exts.add(RNIEXT);
+        exts.add(SIGALGEXT);
+        List<Extension> ocspExts = new ArrayList<Extension>() {{
+            add(new OCSPNonceExtension(16));
+        }};
+        exts.add(new CertStatusReqExtension(StatusRequestType.OCSP,
+                new OCSPStatusRequest(null, ocspExts)));
+        return createTlsRecord(Record.ct_handshake, VER_1_2,
+                createClientHelloMsg(VER_1_2, SID, SUITES, exts));
+    }
+
+    /**
+     * Make a ClientHello using a default status_request and a
+     * status_request_v2 that has a single responder ID in it.
+     */
+    private static ByteBuffer makeStatReqDefV2WithRid() throws IOException {
+        HelloExtensions exts = new HelloExtensions();
+        List<ResponderId> rids = new ArrayList<ResponderId>() {{
+            add(new ResponderId(new X500Principal("CN=Foo")));
+        }};
+        List<CertStatusReqItemV2> itemList = new ArrayList<>(2);
+        itemList.add(new CertStatusReqItemV2(StatusRequestType.OCSP_MULTI,
+                new OCSPStatusRequest(rids, null)));
+        itemList.add(new CertStatusReqItemV2(StatusRequestType.OCSP,
+                new OCSPStatusRequest(rids, null)));
+
+        exts.add(RNIEXT);
+        exts.add(SIGALGEXT);
+        exts.add(new CertStatusReqExtension(StatusRequestType.OCSP,
+                new OCSPStatusRequest(null, null)));
+        exts.add(new CertStatusReqListV2Extension(itemList));
+        return createTlsRecord(Record.ct_handshake, VER_1_2,
+                createClientHelloMsg(VER_1_2, SID, SUITES, exts));
+    }
+
+    /**
+     * Make a ClientHello using a default status_request and a
+     * status_request_v2 that has a single responder ID in it for the
+     * OCSP_MULTI request item and a default OCSP request item.
+     */
+    private static ByteBuffer makeStatReqDefV2MultiWithRidSingleDef()
+            throws IOException {
+        HelloExtensions exts = new HelloExtensions();
+        List<ResponderId> rids = new ArrayList<ResponderId>() {{
+            add(new ResponderId(new X500Principal("CN=Foo")));
+        }};
+        List<CertStatusReqItemV2> itemList = new ArrayList<>(2);
+        itemList.add(new CertStatusReqItemV2(StatusRequestType.OCSP_MULTI,
+                new OCSPStatusRequest(rids, null)));
+        itemList.add(new CertStatusReqItemV2(StatusRequestType.OCSP,
+                new OCSPStatusRequest(null, null)));
+
+        exts.add(RNIEXT);
+        exts.add(SIGALGEXT);
+        exts.add(new CertStatusReqExtension(StatusRequestType.OCSP,
+                new OCSPStatusRequest(null, null)));
+        exts.add(new CertStatusReqListV2Extension(itemList));
+        return createTlsRecord(Record.ct_handshake, VER_1_2,
+                createClientHelloMsg(VER_1_2, SID, SUITES, exts));
+    }
+
+    /**
+     * Make a ClientHello using status_request and status_request_v2 where
+     * all underlying OCSPStatusRequests use responder IDs.
+     */
+    private static ByteBuffer makeStatReqAllWithRid() throws IOException {
+        HelloExtensions exts = new HelloExtensions();
+        List<ResponderId> rids = new ArrayList<ResponderId>() {{
+            add(new ResponderId(new X500Principal("CN=Foo")));
+        }};
+        List<CertStatusReqItemV2> itemList = new ArrayList<>(2);
+        itemList.add(new CertStatusReqItemV2(StatusRequestType.OCSP_MULTI,
+                new OCSPStatusRequest(rids, null)));
+        itemList.add(new CertStatusReqItemV2(StatusRequestType.OCSP,
+                new OCSPStatusRequest(rids, null)));
+
+        exts.add(RNIEXT);
+        exts.add(SIGALGEXT);
+        exts.add(new CertStatusReqExtension(StatusRequestType.OCSP,
+                new OCSPStatusRequest(rids, null)));
+        exts.add(new CertStatusReqListV2Extension(itemList));
+        return createTlsRecord(Record.ct_handshake, VER_1_2,
+                createClientHelloMsg(VER_1_2, SID, SUITES, exts));
+    }
+
+    /**
+     * Make a TLSv1.2 ClientHello multiple CertStatusReqItemV2s of different
+     * types.  One of the middle items should be acceptable while the others
+     * have responder IDs.  The status_request (v1) should also be acceptable
+     * but should be overridden in favor of the status_request_v2.
+     */
+    private static ByteBuffer makeHelloMultiV2andSingle() throws IOException {
+        // Craft the ClientHello byte buffer
+        HelloExtensions exts = new HelloExtensions();
+        List<ResponderId> fooRid = Collections.singletonList(
+                new ResponderId(new X500Principal("CN=Foo")));
+        List<ResponderId> barRid = Collections.singletonList(
+                new ResponderId(new X500Principal("CN=Bar")));
+        List<CertStatusReqItemV2> itemList = new ArrayList<>();
+        itemList.add(new CertStatusReqItemV2(StatusRequestType.OCSP,
+                new OCSPStatusRequest(null, null)));
+        itemList.add(new CertStatusReqItemV2(StatusRequestType.OCSP_MULTI,
+                new OCSPStatusRequest(fooRid, null)));
+        itemList.add(new CertStatusReqItemV2(StatusRequestType.OCSP_MULTI,
+                new OCSPStatusRequest(null, null)));
+        itemList.add(new CertStatusReqItemV2(StatusRequestType.OCSP_MULTI,
+                new OCSPStatusRequest(barRid, null)));
+
+        exts.add(RNIEXT);
+        exts.add(SIGALGEXT);
+        exts.add(new CertStatusReqExtension(StatusRequestType.OCSP,
+                new OCSPStatusRequest(null, null)));
+        exts.add(new CertStatusReqListV2Extension(itemList));
+        return createTlsRecord(Record.ct_handshake, VER_1_2,
+                createClientHelloMsg(VER_1_2, SID, SUITES, exts));
+    }
+
+    /**
+     * Wrap a TLS content message into a TLS record header
+     *
+     * @param contentType a byte containing the content type value
+     * @param pv the protocol version for this record
+     * @param data a byte buffer containing the message data
+     * @return
+     */
+    private static ByteBuffer createTlsRecord(byte contentType,
+            ProtocolVersion pv, ByteBuffer data) {
+        int msgLen = (data != null) ? data.limit() : 0;
+
+        // Allocate enough space to hold the TLS record header + the message
+        ByteBuffer recordBuf = ByteBuffer.allocate(msgLen + 5);
+        recordBuf.put(contentType);
+        recordBuf.putShort((short)pv.v);
+        recordBuf.putShort((short)msgLen);
+        if (msgLen > 0) {
+            recordBuf.put(data);
+        }
+
+        recordBuf.flip();
+        return recordBuf;
+    }
+
+    /**
+     * Craft and encode a ClientHello message as a byte array.
+     *
+     * @param pv the protocol version asserted in the hello message.
+     * @param sessId the session ID for this hello message.
+     * @param suites a list consisting of one or more cipher suite objects
+     * @param extensions a list of HelloExtension objects
+     *
+     * @return a byte array containing the encoded ClientHello message.
+     */
+    private static ByteBuffer createClientHelloMsg(ProtocolVersion pv,
+            SessionId sessId, CipherSuiteList suites,
+            HelloExtensions extensions) throws IOException {
+        ByteBuffer msgBuf;
+
+        HandshakeOutStream hsos =
+                new HandshakeOutStream(new SSLEngineOutputRecord());
+
+        // Construct the client hello object from the first 3 parameters
+        HandshakeMessage.ClientHello cHello =
+                new HandshakeMessage.ClientHello(RNG, pv, sessId, suites,
+                        false);
+
+        // Use the HelloExtensions provided by the caller
+        if (extensions != null) {
+            cHello.extensions = extensions;
+        }
+
+        cHello.send(hsos);
+        msgBuf = ByteBuffer.allocate(hsos.size() + 4);
+
+        // Combine the handshake type with the length
+        msgBuf.putInt((HandshakeMessage.ht_client_hello << 24) |
+                (hsos.size() & 0x00FFFFFF));
+        msgBuf.put(hsos.toByteArray());
+        msgBuf.flip();
+        return msgBuf;
+    }
+
+    /*
+     * If the result indicates that we have outstanding tasks to do,
+     * go ahead and run them in this thread.
+     */
+    private static void runDelegatedTasks(SSLEngineResult result,
+            SSLEngine engine) throws Exception {
+
+        if (result.getHandshakeStatus() == HandshakeStatus.NEED_TASK) {
+            Runnable runnable;
+            while ((runnable = engine.getDelegatedTask()) != null) {
+                if (debug) {
+                    log("\trunning delegated task...");
+                }
+                runnable.run();
+            }
+            HandshakeStatus hsStatus = engine.getHandshakeStatus();
+            if (hsStatus == HandshakeStatus.NEED_TASK) {
+                throw new Exception(
+                    "handshake shouldn't need additional tasks");
+            }
+            if (debug) {
+                log("\tnew HandshakeStatus: " + hsStatus);
+            }
+        }
+    }
+
+    private static void log(String str, SSLEngineResult result) {
+        if (!logging) {
+            return;
+        }
+        HandshakeStatus hsStatus = result.getHandshakeStatus();
+        log(str +
+            result.getStatus() + "/" + hsStatus + ", " +
+            result.bytesConsumed() + "/" + result.bytesProduced() +
+            " bytes");
+        if (hsStatus == HandshakeStatus.FINISHED) {
+            log("\t...ready for application data");
+        }
+    }
+
+    private static void log(String str) {
+        if (logging) {
+            System.out.println(str);
+        }
+    }
+
+    /**
+     * Dump a ByteBuffer as a hexdump to stdout.  The dumping routine will
+     * start at the current position of the buffer and run to its limit.
+     * After completing the dump, the position will be returned to its
+     * starting point.
+     *
+     * @param data the ByteBuffer to dump to stdout.
+     *
+     * @return the hexdump of the byte array.
+     */
+    private static String dumpHexBytes(ByteBuffer data) {
+        StringBuilder sb = new StringBuilder();
+        if (data != null) {
+            int i = 0;
+            data.mark();
+            while (data.hasRemaining()) {
+                if (i % 16 == 0 && i != 0) {
+                    sb.append("\n");
+                }
+                sb.append(String.format("%02X ", data.get()));
+                i++;
+            }
+            data.reset();
+        }
+
+        return sb.toString();
+    }
+
+    /**
+     * Tests the ServerHello for the presence (or not) of the status_request
+     * or status_request_v2 hello extension.  It is assumed that the provided
+     * ByteBuffer has its position set at the first byte of the TLS record
+     * containing the ServerHello and contains the entire hello message.  Upon
+     * successful completion of this method the ByteBuffer will have its
+     * position reset to the initial offset in the buffer.  If an exception is
+     * thrown the position at the time of the exception will be preserved.
+     *
+     * @param statReqPresent true if the status_request hello extension should
+     * be present.
+     * @param statReqV2Present true if the status_request_v2 hello extension
+     * should be present.
+     *
+     * @return true if the ServerHello's extension set matches the presence
+     *      booleans for status_request and status_request_v2.  False if
+     *      not, or if the TLS record or message is of the wrong type.
+     */
+    private static boolean checkServerHello(ByteBuffer data,
+            boolean statReqPresent, boolean statReqV2Present) {
+        boolean hasV1 = false;
+        boolean hasV2 = false;
+        Objects.requireNonNull(data);
+        int startPos = data.position();
+        data.mark();
+
+        // Process the TLS record header
+        int type = Byte.toUnsignedInt(data.get());
+        int ver_major = Byte.toUnsignedInt(data.get());
+        int ver_minor = Byte.toUnsignedInt(data.get());
+        int recLen = Short.toUnsignedInt(data.getShort());
+
+        // Simple sanity checks
+        if (type != 22) {
+            log("Not a handshake: Type = " + type);
+            return false;
+        } else if (recLen > data.remaining()) {
+            log("Incomplete record in buffer: Record length = " + recLen +
+                    ", Remaining = " + data.remaining());
+            return false;
+        }
+
+        // Grab the handshake message header.
+        int msgHdr = data.getInt();
+        int msgType = (msgHdr >> 24) & 0x000000FF;
+        int msgLen = msgHdr & 0x00FFFFFF;
+
+        // More simple sanity checks
+        if (msgType != 2) {
+            log("Not a ServerHello: Type = " + msgType);
+            return false;
+        }
+
+        // Skip over the protocol version and server random
+        data.position(data.position() + 34);
+
+        // Jump past the session ID
+        int sessLen = Byte.toUnsignedInt(data.get());
+        if (sessLen != 0) {
+            data.position(data.position() + sessLen);
+        }
+
+        // Skip the cipher suite and compression method
+        data.position(data.position() + 3);
+
+        // Go through the extensions and look for the request extension
+        // expected by the caller.
+        int extsLen = Short.toUnsignedInt(data.getShort());
+        while (data.position() < recLen + startPos + 5) {
+            int extType = Short.toUnsignedInt(data.getShort());
+            int extLen = Short.toUnsignedInt(data.getShort());
+            hasV1 |= (extType == ExtensionType.EXT_STATUS_REQUEST.id);
+            hasV2 |= (extType == ExtensionType.EXT_STATUS_REQUEST_V2.id);
+            data.position(data.position() + extLen);
+        }
+
+        if (hasV1 != statReqPresent) {
+            log("The status_request extension is " +
+                    "inconsistent with the expected result: expected = " +
+                    statReqPresent + ", actual = " + hasV1);
+        }
+        if (hasV2 != statReqV2Present) {
+            log("The status_request_v2 extension is " +
+                    "inconsistent with the expected result: expected = " +
+                    statReqV2Present + ", actual = " + hasV2);
+        }
+
+        // Reset the position to the initial spot at the start of this method.
+        data.reset();
+
+        return ((hasV1 == statReqPresent) && (hasV2 == statReqV2Present));
+    }
+
+    /**
+     * Creates the PKI components necessary for this test, including
+     * Root CA, Intermediate CA and SSL server certificates, the keystores
+     * for each entity, a client trust store, and starts the OCSP responders.
+     */
+    private static void createPKI() throws Exception {
+        CertificateBuilder cbld = new CertificateBuilder();
+        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
+        keyGen.initialize(2048);
+        KeyStore.Builder keyStoreBuilder =
+                KeyStore.Builder.newInstance("PKCS12", null,
+                        new KeyStore.PasswordProtection(passwd.toCharArray()));
+
+        // Generate Root, IntCA, EE keys
+        KeyPair rootCaKP = keyGen.genKeyPair();
+        log("Generated Root CA KeyPair");
+        KeyPair intCaKP = keyGen.genKeyPair();
+        log("Generated Intermediate CA KeyPair");
+        KeyPair sslKP = keyGen.genKeyPair();
+        log("Generated SSL Cert KeyPair");
+
+        // Set up the Root CA Cert
+        cbld.setSubjectName("CN=Root CA Cert, O=SomeCompany");
+        cbld.setPublicKey(rootCaKP.getPublic());
+        cbld.setSerialNumber(new BigInteger("1"));
+        // Make a 3 year validity starting from 60 days ago
+        long start = System.currentTimeMillis() - TimeUnit.DAYS.toMillis(60);
+        long end = start + TimeUnit.DAYS.toMillis(1085);
+        cbld.setValidity(new Date(start), new Date(end));
+        addCommonExts(cbld, rootCaKP.getPublic(), rootCaKP.getPublic());
+        addCommonCAExts(cbld);
+        // Make our Root CA Cert!
+        X509Certificate rootCert = cbld.build(null, rootCaKP.getPrivate(),
+                "SHA256withRSA");
+        log("Root CA Created:\n" + certInfo(rootCert));
+
+        // Now build a keystore and add the keys and cert
+        rootKeystore = keyStoreBuilder.getKeyStore();
+        java.security.cert.Certificate[] rootChain = {rootCert};
+        rootKeystore.setKeyEntry(ROOT_ALIAS, rootCaKP.getPrivate(),
+                passwd.toCharArray(), rootChain);
+
+        // Now fire up the OCSP responder
+        rootOcsp = new SimpleOCSPServer(rootKeystore, passwd, ROOT_ALIAS, null);
+        rootOcsp.enableLog(debug);
+        rootOcsp.setNextUpdateInterval(3600);
+        rootOcsp.start();
+
+        // Wait 5 seconds for server ready
+        for (int i = 0; (i < 100 && !rootOcsp.isServerReady()); i++) {
+            Thread.sleep(50);
+        }
+        if (!rootOcsp.isServerReady()) {
+            throw new RuntimeException("Server not ready yet");
+        }
+
+        rootOcspPort = rootOcsp.getPort();
+        String rootRespURI = "http://localhost:" + rootOcspPort;
+        log("Root OCSP Responder URI is " + rootRespURI);
+
+        // Now that we have the root keystore and OCSP responder we can
+        // create our intermediate CA.
+        cbld.reset();
+        cbld.setSubjectName("CN=Intermediate CA Cert, O=SomeCompany");
+        cbld.setPublicKey(intCaKP.getPublic());
+        cbld.setSerialNumber(new BigInteger("100"));
+        // Make a 2 year validity starting from 30 days ago
+        start = System.currentTimeMillis() - TimeUnit.DAYS.toMillis(30);
+        end = start + TimeUnit.DAYS.toMillis(730);
+        cbld.setValidity(new Date(start), new Date(end));
+        addCommonExts(cbld, intCaKP.getPublic(), rootCaKP.getPublic());
+        addCommonCAExts(cbld);
+        cbld.addAIAExt(Collections.singletonList(rootRespURI));
+        // Make our Intermediate CA Cert!
+        X509Certificate intCaCert = cbld.build(rootCert, rootCaKP.getPrivate(),
+                "SHA256withRSA");
+        log("Intermediate CA Created:\n" + certInfo(intCaCert));
+
+        // Provide intermediate CA cert revocation info to the Root CA
+        // OCSP responder.
+        Map<BigInteger, SimpleOCSPServer.CertStatusInfo> revInfo =
+            new HashMap<>();
+        revInfo.put(intCaCert.getSerialNumber(),
+                new SimpleOCSPServer.CertStatusInfo(
+                        SimpleOCSPServer.CertStatus.CERT_STATUS_GOOD));
+        rootOcsp.updateStatusDb(revInfo);
+
+        // Now build a keystore and add the keys, chain and root cert as a TA
+        intKeystore = keyStoreBuilder.getKeyStore();
+        java.security.cert.Certificate[] intChain = {intCaCert, rootCert};
+        intKeystore.setKeyEntry(INT_ALIAS, intCaKP.getPrivate(),
+                passwd.toCharArray(), intChain);
+        intKeystore.setCertificateEntry(ROOT_ALIAS, rootCert);
+
+        // Now fire up the Intermediate CA OCSP responder
+        intOcsp = new SimpleOCSPServer(intKeystore, passwd,
+                INT_ALIAS, null);
+        intOcsp.enableLog(debug);
+        intOcsp.setNextUpdateInterval(3600);
+        intOcsp.start();
+
+        // Wait 5 seconds for server ready
+        for (int i = 0; (i < 100 && !intOcsp.isServerReady()); i++) {
+            Thread.sleep(50);
+        }
+        if (!intOcsp.isServerReady()) {
+            throw new RuntimeException("Server not ready yet");
+        }
+
+        intOcspPort = intOcsp.getPort();
+        String intCaRespURI = "http://localhost:" + intOcspPort;
+        log("Intermediate CA OCSP Responder URI is " + intCaRespURI);
+
+        // Last but not least, let's make our SSLCert and add it to its own
+        // Keystore
+        cbld.reset();
+        cbld.setSubjectName("CN=SSLCertificate, O=SomeCompany");
+        cbld.setPublicKey(sslKP.getPublic());
+        cbld.setSerialNumber(new BigInteger("4096"));
+        // Make a 1 year validity starting from 7 days ago
+        start = System.currentTimeMillis() - TimeUnit.DAYS.toMillis(7);
+        end = start + TimeUnit.DAYS.toMillis(365);
+        cbld.setValidity(new Date(start), new Date(end));
+
+        // Add extensions
+        addCommonExts(cbld, sslKP.getPublic(), intCaKP.getPublic());
+        boolean[] kuBits = {true, false, true, false, false, false,
+            false, false, false};
+        cbld.addKeyUsageExt(kuBits);
+        List<String> ekuOids = new ArrayList<>();
+        ekuOids.add("1.3.6.1.5.5.7.3.1");
+        ekuOids.add("1.3.6.1.5.5.7.3.2");
+        cbld.addExtendedKeyUsageExt(ekuOids);
+        cbld.addSubjectAltNameDNSExt(Collections.singletonList("localhost"));
+        cbld.addAIAExt(Collections.singletonList(intCaRespURI));
+        // Make our SSL Server Cert!
+        X509Certificate sslCert = cbld.build(intCaCert, intCaKP.getPrivate(),
+                "SHA256withRSA");
+        log("SSL Certificate Created:\n" + certInfo(sslCert));
+
+        // Provide SSL server cert revocation info to the Intermeidate CA
+        // OCSP responder.
+        revInfo = new HashMap<>();
+        revInfo.put(sslCert.getSerialNumber(),
+                new SimpleOCSPServer.CertStatusInfo(
+                        SimpleOCSPServer.CertStatus.CERT_STATUS_GOOD));
+        intOcsp.updateStatusDb(revInfo);
+
+        // Now build a keystore and add the keys, chain and root cert as a TA
+        serverKeystore = keyStoreBuilder.getKeyStore();
+        java.security.cert.Certificate[] sslChain = {sslCert, intCaCert, rootCert};
+        serverKeystore.setKeyEntry(SSL_ALIAS, sslKP.getPrivate(),
+                passwd.toCharArray(), sslChain);
+        serverKeystore.setCertificateEntry(ROOT_ALIAS, rootCert);
+
+        // And finally a Trust Store for the client
+        trustStore = keyStoreBuilder.getKeyStore();
+        trustStore.setCertificateEntry(ROOT_ALIAS, rootCert);
+    }
+
+    private static void addCommonExts(CertificateBuilder cbld,
+            PublicKey subjKey, PublicKey authKey) throws IOException {
+        cbld.addSubjectKeyIdExt(subjKey);
+        cbld.addAuthorityKeyIdExt(authKey);
+    }
+
+    private static void addCommonCAExts(CertificateBuilder cbld)
+            throws IOException {
+        cbld.addBasicConstraintsExt(true, true, -1);
+        // Set key usage bits for digitalSignature, keyCertSign and cRLSign
+        boolean[] kuBitSettings = {true, false, false, false, false, true,
+            true, false, false};
+        cbld.addKeyUsageExt(kuBitSettings);
+    }
+
+    /**
+     * Helper routine that dumps only a few cert fields rather than
+     * the whole toString() output.
+     *
+     * @param cert an X509Certificate to be displayed
+     *
+     * @return the String output of the issuer, subject and
+     * serial number
+     */
+    private static String certInfo(X509Certificate cert) {
+        StringBuilder sb = new StringBuilder();
+        sb.append("Issuer: ").append(cert.getIssuerX500Principal()).
+                append("\n");
+        sb.append("Subject: ").append(cert.getSubjectX500Principal()).
+                append("\n");
+        sb.append("Serial: ").append(cert.getSerialNumber()).append("\n");
+        return sb.toString();
+    }
+
+    private static class TestCase {
+        public final String testName;
+        public final ByteBuffer data;
+        public final boolean statReqEnabled;
+        public final boolean statReqV2Enabled;
+
+        TestCase(String name, ByteBuffer buffer, boolean srEn, boolean srv2En) {
+            testName = (name != null) ? name : "";
+            data = Objects.requireNonNull(buffer,
+                    "TestCase requires a non-null ByteBuffer");
+            statReqEnabled = srEn;
+            statReqV2Enabled = srv2En;
+        }
+    }
+}
--- a/jdk/test/sun/security/tools/jarsigner/AltProvider.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/sun/security/tools/jarsigner/AltProvider.java	Wed Jul 05 22:05:22 2017 +0200
@@ -55,7 +55,7 @@
         // Compile the provider
         CompilerUtils.compile(
                 MOD_SRC_DIR, MOD_DEST_DIR,
-                "-modulesourcepath",
+                "--module-source-path",
                 MOD_SRC_DIR.toString());
 
         // Create a keystore
@@ -102,22 +102,22 @@
                 0, "loadProviderByClass: org.test.dummy.DummyProvider");
 
         // name in a module
-        testBoth("-J-mp -Jmods " +
+        testBoth("-J--module-path=mods " +
                 "-addprovider Dummy -providerArg full",
                 0, "loadProviderByName: Dummy");
 
         // -providerClass does not work
-        testBoth("-J-mp -Jmods " +
+        testBoth("-J--module-path=mods " +
                 "-providerClass org.test.dummy.DummyProvider -providerArg full",
                 1, "Provider \"org.test.dummy.DummyProvider\" not found");
 
         // -addprovider with class does not work
-        testBoth("-J-mp -Jmods " +
+        testBoth("-J--module-path=mods " +
                 "-addprovider org.test.dummy.DummyProvider -providerArg full",
                 1, "Provider named \"org.test.dummy.DummyProvider\" not found");
 
         // -addprovider without arg does not work
-        testBoth("-J-mp -Jmods " +
+        testBoth("-J--module-path=mods " +
                 "-addprovider Dummy",
                 1, "DUMMYKS not found");
     }
--- a/jdk/test/sun/security/tools/jarsigner/TimestampCheck.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/sun/security/tools/jarsigner/TimestampCheck.java	Wed Jul 05 22:05:22 2017 +0200
@@ -311,6 +311,7 @@
 
             cmd += " " + System.getProperty("test.tool.vm.opts")
                     + " -J-Djava.security.egd=file:/dev/./urandom"
+                    + " -J-Duser.language=en -J-Duser.country=US"
                     + " -debug -keystore " + TSKS + " -storepass changeit"
                     + " -tsa http://localhost:" + port + "/%d"
                     + " -signedjar new_%d.jar " + JAR + " old";
--- a/jdk/test/sun/security/tools/jarsigner/TsacertOptionTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/sun/security/tools/jarsigner/TsacertOptionTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -22,14 +22,13 @@
  */
 
 import jdk.testlibrary.OutputAnalyzer;
-import jdk.testlibrary.ProcessTools;
 import jdk.testlibrary.JarUtils;
 
 /**
  * @test
  * @bug 8024302 8026037
  * @summary The test signs and verifies a jar file with -tsacert option
- * @library /lib/testlibrary
+ * @library /lib/testlibrary warnings
  * @modules java.base/sun.security.pkcs
  *          java.base/sun.security.timestamp
  *          java.base/sun.security.util
@@ -37,29 +36,14 @@
  *          java.management
  * @run main TsacertOptionTest
  */
-public class TsacertOptionTest {
+public class TsacertOptionTest extends Test {
 
-    private static final String FS = System.getProperty("file.separator");
-    private static final String JAVA_HOME = System.getProperty("java.home");
-    private static final String KEYTOOL = JAVA_HOME + FS + "bin" + FS
-            + "keytool";
-    private static final String JARSIGNER = JAVA_HOME + FS + "bin" + FS
-            + "jarsigner";
-    private static final String UNSIGNED_JARFILE = "unsigned.jar";
-    private static final String SIGNED_JARFILE = "signed.jar";
     private static final String FILENAME = TsacertOptionTest.class.getName()
             + ".txt";
-    private static final String PASSWORD = "changeit";
-    private static final String KEYSTORE = "ks.jks";
-    private static final String CA_KEY_ALIAS = "ca";
     private static final String SIGNING_KEY_ALIAS = "sign_alias";
     private static final String TSA_KEY_ALIAS = "ts";
-    private static final String KEY_ALG = "RSA";
-    private static final int KEY_SIZE = 2048;
-    private static final int VALIDITY = 365;
-    private static final String WARNING = "Warning:";
-    private static final String JAR_SIGNED = "jar signed.";
-    private static final String JAR_VERIFIED = "jar verified.";
+
+    private static final String PASSWORD = "changeit";
 
     /**
      * The test signs and verifies a jar file with -tsacert option,
@@ -77,13 +61,8 @@
         Utils.createFiles(FILENAME);
         JarUtils.createJar(UNSIGNED_JARFILE, FILENAME);
 
-        // look for free network port for TSA service
-        int port = jdk.testlibrary.Utils.getFreePort();
-        String host = "127.0.0.1";
-        String tsaUrl = "http://" + host + ":" + port;
-
         // create key pair for jar signing
-        ProcessTools.executeCommand(KEYTOOL,
+        keytool(
                 "-genkey",
                 "-alias", CA_KEY_ALIAS,
                 "-keyalg", KEY_ALG,
@@ -93,7 +72,7 @@
                 "-keypass", PASSWORD,
                 "-dname", "CN=CA",
                 "-validity", Integer.toString(VALIDITY)).shouldHaveExitValue(0);
-        ProcessTools.executeCommand(KEYTOOL,
+        keytool(
                 "-genkey",
                 "-alias", SIGNING_KEY_ALIAS,
                 "-keyalg", KEY_ALG,
@@ -102,14 +81,14 @@
                 "-storepass", PASSWORD,
                 "-keypass", PASSWORD,
                 "-dname", "CN=Test").shouldHaveExitValue(0);
-        ProcessTools.executeCommand(KEYTOOL,
+        keytool(
                 "-certreq",
                 "-alias", SIGNING_KEY_ALIAS,
                 "-keystore", KEYSTORE,
                 "-storepass", PASSWORD,
                 "-keypass", PASSWORD,
                 "-file", "certreq").shouldHaveExitValue(0);
-        ProcessTools.executeCommand(KEYTOOL,
+        keytool(
                 "-gencert",
                 "-alias", CA_KEY_ALIAS,
                 "-keystore", KEYSTORE,
@@ -118,7 +97,7 @@
                 "-validity", Integer.toString(VALIDITY),
                 "-infile", "certreq",
                 "-outfile", "cert").shouldHaveExitValue(0);
-        ProcessTools.executeCommand(KEYTOOL,
+        keytool(
                 "-importcert",
                 "-alias", SIGNING_KEY_ALIAS,
                 "-keystore", KEYSTORE,
@@ -126,24 +105,30 @@
                 "-keypass", PASSWORD,
                 "-file", "cert").shouldHaveExitValue(0);
 
-        // create key pair for TSA service
-        // SubjectInfoAccess extension contains URL to TSA service
-        ProcessTools.executeCommand(KEYTOOL,
-                "-genkey",
-                "-v",
-                "-alias", TSA_KEY_ALIAS,
-                "-keyalg", KEY_ALG,
-                "-keysize", Integer.toString(KEY_SIZE),
-                "-keystore", KEYSTORE,
-                "-storepass", PASSWORD,
-                "-keypass", PASSWORD,
-                "-dname", "CN=TSA",
-                "-ext", "ExtendedkeyUsage:critical=timeStamping",
-                "-ext", "SubjectInfoAccess=timeStamping:URI:" + tsaUrl,
-                "-validity", Integer.toString(VALIDITY)).shouldHaveExitValue(0);
+
+        try (TimestampCheck.Handler tsa = TimestampCheck.Handler.init(0,
+                KEYSTORE)) {
+
+            // look for free network port for TSA service
+            int port = tsa.getPort();
+            String host = "127.0.0.1";
+            String tsaUrl = "http://" + host + ":" + port;
 
-        try (TimestampCheck.Handler tsa = TimestampCheck.Handler.init(port,
-                KEYSTORE);) {
+            // create key pair for TSA service
+            // SubjectInfoAccess extension contains URL to TSA service
+            keytool(
+                    "-genkey",
+                    "-v",
+                    "-alias", TSA_KEY_ALIAS,
+                    "-keyalg", KEY_ALG,
+                    "-keysize", Integer.toString(KEY_SIZE),
+                    "-keystore", KEYSTORE,
+                    "-storepass", PASSWORD,
+                    "-keypass", PASSWORD,
+                    "-dname", "CN=TSA",
+                    "-ext", "ExtendedkeyUsage:critical=timeStamping",
+                    "-ext", "SubjectInfoAccess=timeStamping:URI:" + tsaUrl,
+                    "-validity", Integer.toString(VALIDITY)).shouldHaveExitValue(0);
 
             // start TSA
             tsa.start();
@@ -151,7 +136,7 @@
             // sign jar file
             // specify -tsadigestalg option because
             // TSA server uses SHA-1 digest algorithm
-             OutputAnalyzer analyzer = ProcessTools.executeCommand(JARSIGNER,
+             OutputAnalyzer analyzer = jarsigner(
                     "-J-Dhttp.proxyHost=",
                     "-J-Dhttp.proxyPort=",
                     "-J-Djava.net.useSystemProxies=",
@@ -170,7 +155,7 @@
             analyzer.shouldContain(JAR_SIGNED);
 
             // verify signed jar
-            analyzer = ProcessTools.executeCommand(JARSIGNER,
+            analyzer = jarsigner(
                     "-verbose",
                     "-verify",
                     "-keystore", KEYSTORE,
--- a/jdk/test/sun/security/tools/jarsigner/concise_jarsigner.sh	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/sun/security/tools/jarsigner/concise_jarsigner.sh	Wed Jul 05 22:05:22 2017 +0200
@@ -47,6 +47,8 @@
 # Choose 1024-bit RSA to make sure it runs fine and fast on all platforms. In
 # fact, every keyalg/keysize combination is OK for this test.
 
+TESTTOOLVMOPTS="$TESTTOOLVMOPTS -J-Duser.language=en -J-Duser.country=US"
+
 KS=js.ks
 KT="$TESTJAVA${FS}bin${FS}keytool ${TESTTOOLVMOPTS} -storepass changeit -keypass changeit -keystore $KS -keyalg rsa -keysize 1024"
 JAR="$TESTJAVA${FS}bin${FS}jar ${TESTTOOLVMOPTS}"
--- a/jdk/test/sun/security/tools/jarsigner/default_options.sh	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/sun/security/tools/jarsigner/default_options.sh	Wed Jul 05 22:05:22 2017 +0200
@@ -34,6 +34,8 @@
 PASS=changeit
 export PASS
 
+TESTTOOLVMOPTS="$TESTTOOLVMOPTS -J-Duser.language=en -J-Duser.country=US"
+
 KS=ks
 KEYTOOL="$TESTJAVA/bin/keytool ${TESTTOOLVMOPTS} -storepass:env PASS -keypass:env PASS -keystore $KS"
 JAR="$TESTJAVA/bin/jar ${TESTTOOLVMOPTS}"
--- a/jdk/test/sun/security/tools/jarsigner/ts.sh	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/sun/security/tools/jarsigner/ts.sh	Wed Jul 05 22:05:22 2017 +0200
@@ -94,10 +94,10 @@
         $KT -alias ca -gencert -ext eku:critical=cs | \
         $KT -alias tsbad3 -importcert
 
-EXTRAOPTS="-XaddExports:java.base/sun.security.pkcs=ALL-UNNAMED \
- -XaddExports:java.base/sun.security.timestamp=ALL-UNNAMED \
- -XaddExports:java.base/sun.security.x509=ALL-UNNAMED \
- -XaddExports:java.base/sun.security.util=ALL-UNNAMED"
+EXTRAOPTS="--add-exports java.base/sun.security.pkcs=ALL-UNNAMED \
+ --add-exports java.base/sun.security.timestamp=ALL-UNNAMED \
+ --add-exports java.base/sun.security.x509=ALL-UNNAMED \
+ --add-exports java.base/sun.security.util=ALL-UNNAMED"
 $JAVAC ${EXTRAOPTS} -d . ${TESTSRC}/TimestampCheck.java
 $JAVA ${TESTVMOPTS} ${EXTRAOPTS} "-Dtest.tool.vm.opts=${TESTTOOLVMOPTS}" TimestampCheck
 
--- a/jdk/test/sun/security/tools/jarsigner/warnings/AliasNotInStoreTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/sun/security/tools/jarsigner/warnings/AliasNotInStoreTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -22,7 +22,6 @@
  */
 
 import jdk.testlibrary.OutputAnalyzer;
-import jdk.testlibrary.ProcessTools;
 import jdk.testlibrary.JarUtils;
 
 /**
@@ -51,7 +50,7 @@
         JarUtils.createJar(UNSIGNED_JARFILE, FIRST_FILE);
 
         // create first key pair for signing
-        ProcessTools.executeCommand(KEYTOOL,
+        keytool(
                 "-genkey",
                 "-alias", FIRST_KEY_ALIAS,
                 "-keyalg", KEY_ALG,
@@ -63,7 +62,7 @@
                 "-validity", Integer.toString(VALIDITY)).shouldHaveExitValue(0);
 
         // create second key pair for signing
-        ProcessTools.executeCommand(KEYTOOL,
+        keytool(
                 "-genkey",
                 "-alias", SECOND_KEY_ALIAS,
                 "-keyalg", KEY_ALG,
@@ -75,7 +74,7 @@
                 "-validity", Integer.toString(VALIDITY)).shouldHaveExitValue(0);
 
         // sign jar with first key
-        OutputAnalyzer analyzer = ProcessTools.executeCommand(JARSIGNER,
+        OutputAnalyzer analyzer = jarsigner(
                 "-keystore", BOTH_KEYS_KEYSTORE,
                 "-storepass", PASSWORD,
                 "-keypass", PASSWORD,
@@ -92,7 +91,7 @@
         JarUtils.updateJar(SIGNED_JARFILE, UPDATED_SIGNED_JARFILE, SECOND_FILE);
 
         // sign jar with second key
-        analyzer = ProcessTools.executeCommand(JARSIGNER,
+        analyzer = jarsigner(
                 "-keystore", BOTH_KEYS_KEYSTORE,
                 "-storepass", PASSWORD,
                 "-keypass", PASSWORD,
@@ -102,7 +101,7 @@
         checkSigning(analyzer);
 
         // create keystore that contains only first key
-        ProcessTools.executeCommand(KEYTOOL,
+        keytool(
                 "-importkeystore",
                 "-srckeystore", BOTH_KEYS_KEYSTORE,
                 "-srcalias", FIRST_KEY_ALIAS,
@@ -116,7 +115,7 @@
         // verify jar with keystore that contains only first key in strict mode,
         // so there is signed entry (FirstClass.class) that is not signed
         // by any alias in the keystore
-        analyzer = ProcessTools.executeCommand(JARSIGNER,
+        analyzer = jarsigner(
                 "-verify",
                 "-verbose",
                 "-keystore", FIRST_KEY_KEYSTORE,
@@ -128,7 +127,7 @@
                 ALIAS_NOT_IN_STORE_VERIFYING_WARNING);
 
         // verify jar with keystore that contains only first key in strict mode
-        analyzer = ProcessTools.executeCommand(JARSIGNER,
+        analyzer = jarsigner(
                 "-verify",
                 "-verbose",
                 "-strict",
--- a/jdk/test/sun/security/tools/jarsigner/warnings/BadExtendedKeyUsageTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/sun/security/tools/jarsigner/warnings/BadExtendedKeyUsageTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -22,7 +22,6 @@
  */
 
 import jdk.testlibrary.OutputAnalyzer;
-import jdk.testlibrary.ProcessTools;
 import jdk.testlibrary.JarUtils;
 
 /**
@@ -52,7 +51,7 @@
 
         // create a certificate whose signer certificate's
         // ExtendedKeyUsage extension doesn't allow code signing
-        ProcessTools.executeCommand(KEYTOOL,
+        keytool(
                 "-genkey",
                 "-alias", KEY_ALIAS,
                 "-keyalg", KEY_ALG,
@@ -65,7 +64,7 @@
                 "-validity", Integer.toString(VALIDITY)).shouldHaveExitValue(0);
 
         // sign jar
-        OutputAnalyzer analyzer = ProcessTools.executeCommand(JARSIGNER,
+        OutputAnalyzer analyzer = jarsigner(
                 "-verbose",
                 "-keystore", KEYSTORE,
                 "-storepass", PASSWORD,
@@ -77,7 +76,7 @@
         checkSigning(analyzer, BAD_EXTENDED_KEY_USAGE_SIGNING_WARNING);
 
         // verify signed jar
-        analyzer = ProcessTools.executeCommand(JARSIGNER,
+        analyzer = jarsigner(
                 "-verify",
                 "-verbose",
                 "-keystore", KEYSTORE,
@@ -88,7 +87,7 @@
         checkVerifying(analyzer, 0, BAD_EXTENDED_KEY_USAGE_VERIFYING_WARNING);
 
         // verity signed jar in strict mode
-        analyzer = ProcessTools.executeCommand(JARSIGNER,
+        analyzer = jarsigner(
                 "-verify",
                 "-verbose",
                 "-strict",
--- a/jdk/test/sun/security/tools/jarsigner/warnings/BadKeyUsageTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/sun/security/tools/jarsigner/warnings/BadKeyUsageTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -22,7 +22,6 @@
  */
 
 import jdk.testlibrary.OutputAnalyzer;
-import jdk.testlibrary.ProcessTools;
 import jdk.testlibrary.JarUtils;
 
 /**
@@ -53,7 +52,7 @@
 
         // create a certificate whose signer certificate's KeyUsage extension
         // doesn't allow code signing
-        ProcessTools.executeCommand(KEYTOOL,
+        keytool(
                 "-genkey",
                 "-alias", KEY_ALIAS,
                 "-keyalg", KEY_ALG,
@@ -66,7 +65,7 @@
                 "-validity", Integer.toString(VALIDITY)).shouldHaveExitValue(0);
 
         // sign jar
-        OutputAnalyzer analyzer = ProcessTools.executeCommand(JARSIGNER,
+        OutputAnalyzer analyzer = jarsigner(
                 "-verbose",
                 "-keystore", KEYSTORE,
                 "-storepass", PASSWORD,
@@ -78,7 +77,7 @@
         checkSigning(analyzer, BAD_KEY_USAGE_SIGNING_WARNING);
 
         // verify signed jar
-        analyzer = ProcessTools.executeCommand(JARSIGNER,
+        analyzer = jarsigner(
                 "-verify",
                 "-verbose",
                 "-keystore", KEYSTORE,
@@ -89,7 +88,7 @@
         checkVerifying(analyzer, 0, BAD_KEY_USAGE_VERIFYING_WARNING);
 
         // verify signed jar in strict mode
-        analyzer = ProcessTools.executeCommand(JARSIGNER,
+        analyzer = jarsigner(
                 "-verify",
                 "-verbose",
                 "-strict",
--- a/jdk/test/sun/security/tools/jarsigner/warnings/BadNetscapeCertTypeTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/sun/security/tools/jarsigner/warnings/BadNetscapeCertTypeTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -22,7 +22,6 @@
  */
 
 import jdk.testlibrary.OutputAnalyzer;
-import jdk.testlibrary.ProcessTools;
 import jdk.testlibrary.JarUtils;
 
 import java.nio.file.Files;
@@ -67,7 +66,7 @@
         JarUtils.createJar(UNSIGNED_JARFILE, FIRST_FILE);
 
         // sign jar
-        OutputAnalyzer analyzer = ProcessTools.executeCommand(JARSIGNER,
+        OutputAnalyzer analyzer = jarsigner(
                 "-verbose",
                 "-keystore", NETSCAPE_KEYSTORE,
                 "-storepass", PASSWORD,
@@ -79,7 +78,7 @@
         checkSigning(analyzer, BAD_NETSCAPE_CERT_TYPE_SIGNING_WARNING);
 
         // verify signed jar
-        analyzer = ProcessTools.executeCommand(JARSIGNER,
+        analyzer = jarsigner(
                 "-verify",
                 "-verbose",
                 "-keystore", NETSCAPE_KEYSTORE,
@@ -90,7 +89,7 @@
         checkVerifying(analyzer, 0, BAD_NETSCAPE_CERT_TYPE_VERIFYING_WARNING);
 
         // verify signed jar in strict mode
-        analyzer = ProcessTools.executeCommand(JARSIGNER,
+        analyzer = jarsigner(
                 "-verify",
                 "-verbose",
                 "-strict",
--- a/jdk/test/sun/security/tools/jarsigner/warnings/ChainNotValidatedTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/sun/security/tools/jarsigner/warnings/ChainNotValidatedTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -55,7 +55,7 @@
         // create self-signed certificate whose BasicConstraints extension
         // is set to false, so the certificate may not be used
         // as a parent certificate (certpath validation should fail)
-        ProcessTools.executeCommand(KEYTOOL,
+        keytool(
                 "-genkeypair",
                 "-alias", CA_KEY_ALIAS,
                 "-keyalg", KEY_ALG,
@@ -70,7 +70,7 @@
         // create a certificate that is signed by self-signed certificate
         // despite of it may not be used as a parent certificate
         // (certpath validation should fail)
-        ProcessTools.executeCommand(KEYTOOL,
+        keytool(
                 "-genkeypair",
                 "-alias", KEY_ALIAS,
                 "-keyalg", KEY_ALG,
@@ -82,7 +82,7 @@
                 "-ext", "BasicConstraints:critical=ca:false",
                 "-validity", Integer.toString(VALIDITY)).shouldHaveExitValue(0);
 
-        ProcessTools.executeCommand(KEYTOOL,
+        keytool(
                 "-certreq",
                 "-alias", KEY_ALIAS,
                 "-keystore", KEYSTORE,
@@ -90,7 +90,7 @@
                 "-keypass", PASSWORD,
                 "-file", CERT_REQUEST_FILENAME).shouldHaveExitValue(0);
 
-        ProcessTools.executeCommand(KEYTOOL,
+        keytool(
                 "-gencert",
                 "-alias", CA_KEY_ALIAS,
                 "-keystore", KEYSTORE,
@@ -100,7 +100,7 @@
                 "-validity", Integer.toString(VALIDITY),
                 "-outfile", CERT_FILENAME).shouldHaveExitValue(0);
 
-        ProcessTools.executeCommand(KEYTOOL,
+        keytool(
                 "-importcert",
                 "-alias", KEY_ALIAS,
                 "-keystore", KEYSTORE,
@@ -129,7 +129,7 @@
         ProcessTools.executeCommand(pb).shouldHaveExitValue(0);
 
         // remove CA certificate
-        ProcessTools.executeCommand(KEYTOOL,
+        keytool(
                 "-delete",
                 "-alias", CA_KEY_ALIAS,
                 "-keystore", KEYSTORE,
@@ -137,7 +137,7 @@
                 "-keypass", PASSWORD).shouldHaveExitValue(0);
 
         // sign jar
-        OutputAnalyzer analyzer = ProcessTools.executeCommand(JARSIGNER,
+        OutputAnalyzer analyzer = jarsigner(
                 "-keystore", KEYSTORE,
                 "-storepass", PASSWORD,
                 "-keypass", PASSWORD,
@@ -149,7 +149,7 @@
         checkSigning(analyzer, CHAIN_NOT_VALIDATED_SIGNING_WARNING);
 
         // verify signed jar
-        analyzer = ProcessTools.executeCommand(JARSIGNER,
+        analyzer = jarsigner(
                 "-verify",
                 "-verbose",
                 "-keystore", KEYSTORE,
@@ -161,7 +161,7 @@
         checkVerifying(analyzer, 0, CHAIN_NOT_VALIDATED_VERIFYING_WARNING);
 
         // verify signed jar in strict mode
-        analyzer = ProcessTools.executeCommand(JARSIGNER,
+        analyzer = jarsigner(
                 "-verify",
                 "-verbose",
                 "-strict",
--- a/jdk/test/sun/security/tools/jarsigner/warnings/HasExpiredCertTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/sun/security/tools/jarsigner/warnings/HasExpiredCertTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -22,7 +22,6 @@
  */
 
 import jdk.testlibrary.OutputAnalyzer;
-import jdk.testlibrary.ProcessTools;
 import jdk.testlibrary.JarUtils;
 
 /**
@@ -52,7 +51,7 @@
         JarUtils.createJar(UNSIGNED_JARFILE, FIRST_FILE);
 
         // create key pair for jar signing
-        ProcessTools.executeCommand(KEYTOOL,
+        keytool(
                 "-genkey",
                 "-alias", KEY_ALIAS,
                 "-keyalg", KEY_ALG,
@@ -66,7 +65,7 @@
                 .shouldHaveExitValue(0);
 
         // sign jar
-        OutputAnalyzer analyzer = ProcessTools.executeCommand(JARSIGNER,
+        OutputAnalyzer analyzer = jarsigner(
                 "-keystore", KEYSTORE,
                 "-storepass", PASSWORD,
                 "-keypass", PASSWORD,
@@ -77,7 +76,7 @@
         checkSigning(analyzer, HAS_EXPIRED_CERT_SIGNING_WARNING);
 
         // verify signed jar
-        analyzer = ProcessTools.executeCommand(JARSIGNER,
+        analyzer = jarsigner(
                 "-verify",
                 "-verbose",
                 "-keystore", KEYSTORE,
@@ -87,7 +86,7 @@
 
         checkVerifying(analyzer, 0, HAS_EXPIRED_CERT_VERIFYING_WARNING);
 
-        analyzer = ProcessTools.executeCommand(JARSIGNER,
+        analyzer = jarsigner(
                 "-verify",
                 "-strict",
                 "-keystore", KEYSTORE,
--- a/jdk/test/sun/security/tools/jarsigner/warnings/HasExpiringCertTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/sun/security/tools/jarsigner/warnings/HasExpiringCertTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -22,7 +22,6 @@
  */
 
 import jdk.testlibrary.OutputAnalyzer;
-import jdk.testlibrary.ProcessTools;
 import jdk.testlibrary.JarUtils;
 
 /**
@@ -52,7 +51,7 @@
         JarUtils.createJar(UNSIGNED_JARFILE, FIRST_FILE);
 
         // create key pair for jar signing
-        ProcessTools.executeCommand(KEYTOOL,
+        keytool(
                 "-genkey",
                 "-alias", KEY_ALIAS,
                 "-keyalg", KEY_ALG,
@@ -65,7 +64,7 @@
                 .shouldHaveExitValue(0);
 
         // sign jar
-        OutputAnalyzer analyzer = ProcessTools.executeCommand(JARSIGNER,
+        OutputAnalyzer analyzer = jarsigner(
                 "-keystore", KEYSTORE,
                 "-verbose",
                 "-storepass", PASSWORD,
@@ -77,7 +76,7 @@
         checkSigning(analyzer, HAS_EXPIRING_CERT_SIGNING_WARNING);
 
         // verify signed jar
-        analyzer = ProcessTools.executeCommand(JARSIGNER,
+        analyzer = jarsigner(
                 "-verify",
                 "-verbose",
                 "-keystore", KEYSTORE,
@@ -89,7 +88,7 @@
         checkVerifying(analyzer, 0, HAS_EXPIRING_CERT_VERIFYING_WARNING);
 
         // verify signed jar in strict mode
-        analyzer = ProcessTools.executeCommand(JARSIGNER,
+        analyzer = jarsigner(
                 "-verify",
                 "-verbose",
                 "-strict",
--- a/jdk/test/sun/security/tools/jarsigner/warnings/HasUnsignedEntryTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/sun/security/tools/jarsigner/warnings/HasUnsignedEntryTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -22,7 +22,6 @@
  */
 
 import jdk.testlibrary.OutputAnalyzer;
-import jdk.testlibrary.ProcessTools;
 import jdk.testlibrary.JarUtils;
 
 /**
@@ -51,7 +50,7 @@
         JarUtils.createJar(UNSIGNED_JARFILE, FIRST_FILE);
 
         // create key pair for signing
-        ProcessTools.executeCommand(KEYTOOL,
+        keytool(
                 "-genkey",
                 "-alias", KEY_ALIAS,
                 "-keyalg", KEY_ALG,
@@ -63,7 +62,7 @@
                 "-validity", Integer.toString(VALIDITY)).shouldHaveExitValue(0);
 
         // sign jar
-        OutputAnalyzer analyzer = ProcessTools.executeCommand(JARSIGNER,
+        OutputAnalyzer analyzer = jarsigner(
                 "-verbose",
                 "-keystore", KEYSTORE,
                 "-storepass", PASSWORD,
@@ -82,7 +81,7 @@
         JarUtils.updateJar(SIGNED_JARFILE, UPDATED_SIGNED_JARFILE, SECOND_FILE);
 
         // verify jar
-        analyzer = ProcessTools.executeCommand(JARSIGNER,
+        analyzer = jarsigner(
                 "-verify",
                 "-verbose",
                 "-keystore", KEYSTORE,
@@ -93,7 +92,7 @@
         checkVerifying(analyzer, 0, HAS_UNSIGNED_ENTRY_VERIFYING_WARNING);
 
         // verify jar in strict mode
-        analyzer = ProcessTools.executeCommand(JARSIGNER,
+        analyzer = jarsigner(
                 "-verify",
                 "-verbose",
                 "-strict",
--- a/jdk/test/sun/security/tools/jarsigner/warnings/MultipleWarningsTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/sun/security/tools/jarsigner/warnings/MultipleWarningsTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -22,7 +22,6 @@
  */
 
 import jdk.testlibrary.OutputAnalyzer;
-import jdk.testlibrary.ProcessTools;
 import jdk.testlibrary.JarUtils;
 
 /**
@@ -56,7 +55,7 @@
 
         // create first expired certificate
         // whose ExtendedKeyUsage extension does not allow code signing
-        ProcessTools.executeCommand(KEYTOOL,
+        keytool(
                 "-genkey",
                 "-alias", FIRST_KEY_ALIAS,
                 "-keyalg", KEY_ALG,
@@ -71,7 +70,7 @@
 
         // create second expired certificate
         // whose KeyUsage extension does not allow code signing
-        ProcessTools.executeCommand(KEYTOOL,
+        keytool(
                 "-genkey",
                 "-alias", SECOND_KEY_ALIAS,
                 "-keyalg", KEY_ALG,
@@ -85,7 +84,7 @@
                 "-validity", Integer.toString(VALIDITY)).shouldHaveExitValue(0);
 
         // sign jar with first key
-        OutputAnalyzer analyzer = ProcessTools.executeCommand(JARSIGNER,
+        OutputAnalyzer analyzer = jarsigner(
                 "-keystore", KEYSTORE,
                 "-storepass", PASSWORD,
                 "-keypass", PASSWORD,
@@ -100,7 +99,7 @@
         JarUtils.updateJar(SIGNED_JARFILE, UPDATED_SIGNED_JARFILE, SECOND_FILE);
 
         // verify jar with second key
-        analyzer = ProcessTools.executeCommand(JARSIGNER,
+        analyzer = jarsigner(
                 "-verify",
                 "-keystore", KEYSTORE,
                 "-storepass", PASSWORD,
@@ -114,7 +113,7 @@
                 NOT_SIGNED_BY_ALIAS_VERIFYING_WARNING);
 
         // verify jar with second key in strict mode
-        analyzer = ProcessTools.executeCommand(JARSIGNER,
+        analyzer = jarsigner(
                 "-verify",
                 "-strict",
                 "-keystore", KEYSTORE,
@@ -134,7 +133,7 @@
                 NOT_SIGNED_BY_ALIAS_VERIFYING_WARNING);
 
         // verify jar with non-exisiting alias
-        analyzer = ProcessTools.executeCommand(JARSIGNER,
+        analyzer = jarsigner(
                 "-verify",
                 "-keystore", KEYSTORE,
                 "-storepass", PASSWORD,
@@ -148,7 +147,7 @@
                 NOT_SIGNED_BY_ALIAS_VERIFYING_WARNING);
 
         // verify jar with non-exisiting alias in strict mode
-        analyzer = ProcessTools.executeCommand(JARSIGNER,
+        analyzer = jarsigner(
                 "-verify",
                 "-strict",
                 "-keystore", KEYSTORE,
--- a/jdk/test/sun/security/tools/jarsigner/warnings/NoTimestampTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/sun/security/tools/jarsigner/warnings/NoTimestampTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -23,7 +23,6 @@
 
 import java.util.Date;
 import jdk.testlibrary.OutputAnalyzer;
-import jdk.testlibrary.ProcessTools;
 import jdk.testlibrary.JarUtils;
 
 /**
@@ -57,7 +56,7 @@
                 * 24 * 60 * 60 * 1000L);
 
         // create key pair
-        ProcessTools.executeCommand(KEYTOOL,
+        keytool(
                 "-genkey",
                 "-alias", KEY_ALIAS,
                 "-keyalg", KEY_ALG,
@@ -69,7 +68,7 @@
                 "-validity", Integer.toString(VALIDITY));
 
         // sign jar file
-        OutputAnalyzer analyzer = ProcessTools.executeCommand(JARSIGNER,
+        OutputAnalyzer analyzer = jarsigner(
                 "-J-Duser.timezone=" + timezone,
                 "-keystore", KEYSTORE,
                 "-storepass", PASSWORD,
@@ -83,7 +82,7 @@
         checkSigning(analyzer, warning);
 
         // verify signed jar
-        analyzer = ProcessTools.executeCommand(JARSIGNER,
+        analyzer = jarsigner(
                 "-J-Duser.timezone=" + timezone,
                 "-verify",
                 "-keystore", KEYSTORE,
@@ -96,7 +95,7 @@
         checkVerifying(analyzer, 0, warning);
 
         // verify signed jar in strict mode
-        analyzer = ProcessTools.executeCommand(JARSIGNER,
+        analyzer = jarsigner(
                 "-J-Duser.timezone=" + timezone,
                 "-verify",
                 "-strict",
--- a/jdk/test/sun/security/tools/jarsigner/warnings/NotSignedByAliasTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/sun/security/tools/jarsigner/warnings/NotSignedByAliasTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -22,7 +22,6 @@
  */
 
 import jdk.testlibrary.OutputAnalyzer;
-import jdk.testlibrary.ProcessTools;
 import jdk.testlibrary.JarUtils;
 
 /**
@@ -50,7 +49,7 @@
         JarUtils.createJar(UNSIGNED_JARFILE, FIRST_FILE);
 
         // create first key pair for signing
-        ProcessTools.executeCommand(KEYTOOL,
+        keytool(
                 "-genkey",
                 "-alias", FIRST_KEY_ALIAS,
                 "-keyalg", KEY_ALG,
@@ -62,7 +61,7 @@
                 "-validity", Integer.toString(VALIDITY)).shouldHaveExitValue(0);
 
         // create first key pair for signing
-        ProcessTools.executeCommand(KEYTOOL,
+        keytool(
                 "-genkey",
                 "-alias", SECOND_KEY_ALIAS,
                 "-keyalg", KEY_ALG,
@@ -74,7 +73,7 @@
                 "-validity", Integer.toString(VALIDITY)).shouldHaveExitValue(0);
 
         // sign jar with first key
-        OutputAnalyzer analyzer = ProcessTools.executeCommand(JARSIGNER,
+        OutputAnalyzer analyzer = jarsigner(
                 "-keystore", KEYSTORE,
                 "-storepass", PASSWORD,
                 "-keypass", PASSWORD,
@@ -85,7 +84,7 @@
         checkSigning(analyzer);
 
         // verify jar with second key
-        analyzer = ProcessTools.executeCommand(JARSIGNER,
+        analyzer = jarsigner(
                 "-verify",
                 "-keystore", KEYSTORE,
                 "-storepass", PASSWORD,
@@ -96,7 +95,7 @@
         checkVerifying(analyzer, 0, NOT_SIGNED_BY_ALIAS_VERIFYING_WARNING);
 
         // verify jar with second key in strict mode
-        analyzer = ProcessTools.executeCommand(JARSIGNER,
+        analyzer = jarsigner(
                 "-verify",
                 "-strict",
                 "-keystore", KEYSTORE,
@@ -109,7 +108,7 @@
                 NOT_SIGNED_BY_ALIAS_VERIFYING_WARNING);
 
         // verify jar with non-existing alias
-        analyzer = ProcessTools.executeCommand(JARSIGNER,
+        analyzer = jarsigner(
                 "-verify",
                 "-keystore", KEYSTORE,
                 "-storepass", PASSWORD,
@@ -120,7 +119,7 @@
         checkVerifying(analyzer, 0, NOT_SIGNED_BY_ALIAS_VERIFYING_WARNING);
 
         // verify jar with non-existing alias in strict mode
-        analyzer = ProcessTools.executeCommand(JARSIGNER,
+        analyzer = jarsigner(
                 "-verify",
                 "-strict",
                 "-keystore", KEYSTORE,
--- a/jdk/test/sun/security/tools/jarsigner/warnings/NotYetValidCertTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/sun/security/tools/jarsigner/warnings/NotYetValidCertTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -22,7 +22,6 @@
  */
 
 import jdk.testlibrary.OutputAnalyzer;
-import jdk.testlibrary.ProcessTools;
 import jdk.testlibrary.JarUtils;
 
 /**
@@ -50,7 +49,7 @@
         JarUtils.createJar(UNSIGNED_JARFILE, FIRST_FILE);
 
         // create certificate that will be valid only tomorrow
-        ProcessTools.executeCommand(KEYTOOL,
+        keytool(
                 "-genkey",
                 "-alias", KEY_ALIAS,
                 "-keyalg", KEY_ALG,
@@ -63,7 +62,7 @@
                 "-validity", Integer.toString(VALIDITY));
 
         // sign jar
-        OutputAnalyzer analyzer = ProcessTools.executeCommand(JARSIGNER,
+        OutputAnalyzer analyzer = jarsigner(
                 "-keystore", KEYSTORE,
                 "-storepass", PASSWORD,
                 "-keypass", PASSWORD,
@@ -74,7 +73,7 @@
         checkSigning(analyzer, NOT_YET_VALID_CERT_SIGNING_WARNING);
 
         // verify signed jar
-        analyzer = ProcessTools.executeCommand(JARSIGNER,
+        analyzer = jarsigner(
                 "-verify",
                 "-verbose",
                 "-keystore", KEYSTORE,
@@ -86,7 +85,7 @@
         checkVerifying(analyzer, 0, NOT_YET_VALID_CERT_VERIFYING_WARNING);
 
         // verify jar in strict mode
-        analyzer = ProcessTools.executeCommand(JARSIGNER,
+        analyzer = jarsigner(
                 "-verify",
                 "-verbose",
                 "-strict",
--- a/jdk/test/sun/security/tools/jarsigner/warnings/Test.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/sun/security/tools/jarsigner/warnings/Test.java	Wed Jul 05 22:05:22 2017 +0200
@@ -22,6 +22,11 @@
  */
 
 import jdk.testlibrary.OutputAnalyzer;
+import jdk.testlibrary.ProcessTools;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
 
 /**
  * Base class.
@@ -175,4 +180,21 @@
         }
         analyzer.shouldContain(JAR_SIGNED);
     }
+
+    protected OutputAnalyzer keytool(String... cmd) throws Throwable {
+        return tool(KEYTOOL, cmd);
+    }
+
+    protected OutputAnalyzer jarsigner(String... cmd) throws Throwable {
+        return tool(JARSIGNER, cmd);
+    }
+
+    private OutputAnalyzer tool(String tool, String... args) throws Throwable {
+        List<String> cmd = new ArrayList<>();
+        cmd.add(tool);
+        cmd.add("-J-Duser.language=en");
+        cmd.add("-J-Duser.country=US");
+        cmd.addAll(Arrays.asList(args));
+        return ProcessTools.executeCommand(cmd.toArray(new String[cmd.size()]));
+    }
 }
--- a/jdk/test/sun/security/tools/jarsigner/weaksize.sh	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/sun/security/tools/jarsigner/weaksize.sh	Wed Jul 05 22:05:22 2017 +0200
@@ -31,6 +31,8 @@
   TESTJAVA=`dirname $JAVAC_CMD`/..
 fi
 
+TESTTOOLVMOPTS="$TESTTOOLVMOPTS -J-Duser.language=en -J-Duser.country=US"
+
 # The sigalg used is MD2withRSA, which is obsolete.
 
 KT="$TESTJAVA/bin/keytool ${TESTTOOLVMOPTS} -keystore ks
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/sun/security/tools/keytool/CacertsOption.java	Wed Jul 05 22:05:22 2017 +0200
@@ -0,0 +1,95 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8162739
+ * @summary Create new keytool option to access cacerts file
+ * @modules java.base/sun.security.tools.keytool
+ *          java.base/sun.security.tools
+ * @run main/othervm -Duser.language=en -Duser.country=US CacertsOption
+ */
+
+import sun.security.tools.KeyStoreUtil;
+import sun.security.tools.keytool.Main;
+
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.PrintStream;
+import java.security.KeyStore;
+import java.util.Collections;
+
+public class CacertsOption {
+
+    public static void main(String[] args) throws Exception {
+
+        run("-help -list");
+        if (!msg.contains("-cacerts")) {
+            throw new Exception("No cacerts in help:\n" + msg);
+        }
+
+        String cacerts = KeyStoreUtil.getCacerts();
+
+        run("-list -keystore " + cacerts);
+        if (!msg.contains("Warning:")) {
+            throw new Exception("No warning in output:\n" + msg);
+        }
+
+        run("-list -cacerts");
+        KeyStore ks = KeyStore.getInstance(new File(cacerts), (char[])null);
+        for (String alias: Collections.list(ks.aliases())) {
+            if (!msg.contains(alias)) {
+                throw new Exception(alias + " not found in\n" + msg);
+            }
+        }
+
+        try {
+            run("-list -cacerts -storetype jks");
+            throw new Exception("Should fail");
+        } catch (IllegalArgumentException iae) {
+            if (!msg.contains("cannot be used with")) {
+                throw new Exception("Bad error msg\n" + msg);
+            }
+        }
+    }
+
+    private static String msg = null;
+
+    private static void run(String cmd) throws Exception {
+        msg = null;
+        cmd += " -storepass changeit -debug";
+        ByteArrayOutputStream bout = new ByteArrayOutputStream();
+        PrintStream ps = new PrintStream(bout);
+        PrintStream oldOut = System.out;
+        PrintStream oldErr = System.err;
+        try {
+            System.setOut(ps);
+            System.setErr(ps);
+            Main.main(cmd.split(" "));
+        } finally {
+            System.setErr(oldErr);
+            System.setOut(oldOut);
+            msg = new String(bout.toByteArray());
+        }
+    }
+}
--- a/jdk/test/sun/security/tools/keytool/autotest.sh	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/sun/security/tools/keytool/autotest.sh	Wed Jul 05 22:05:22 2017 +0200
@@ -100,9 +100,9 @@
 
 echo "Using NSS lib at $LIBNAME"
 
-EXTRAOPTS="-XaddExports:java.base/sun.security.tools.keytool=ALL-UNNAMED \
- -XaddExports:java.base/sun.security.util=ALL-UNNAMED \
- -XaddExports:java.base/sun.security.x509=ALL-UNNAMED"
+EXTRAOPTS="--add-exports java.base/sun.security.tools.keytool=ALL-UNNAMED \
+ --add-exports java.base/sun.security.util=ALL-UNNAMED \
+ --add-exports java.base/sun.security.x509=ALL-UNNAMED"
 
 ${COMPILEJAVA}${FS}bin${FS}javac ${TESTJAVACOPTS} ${TESTTOOLVMOPTS} ${EXTRAOPTS} -d . -XDignore.symbol.file \
         ${TESTSRC}${FS}KeyToolTest.java || exit 10
--- a/jdk/test/sun/security/tools/keytool/default_options.sh	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/sun/security/tools/keytool/default_options.sh	Wed Jul 05 22:05:22 2017 +0200
@@ -31,6 +31,8 @@
   TESTJAVA=`dirname $JAVAC_CMD`/..
 fi
 
+TESTTOOLVMOPTS="$TESTTOOLVMOPTS -J-Duser.language=en -J-Duser.country=US"
+
 KS=ks
 KEYTOOL="$TESTJAVA/bin/keytool ${TESTTOOLVMOPTS}"
 
--- a/jdk/test/sun/security/tools/keytool/file-in-help.sh	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/sun/security/tools/keytool/file-in-help.sh	Wed Jul 05 22:05:22 2017 +0200
@@ -42,7 +42,8 @@
     ;;
 esac
 
-LANG=C
+TESTTOOLVMOPTS="$TESTTOOLVMOPTS -J-Duser.language=en -J-Duser.country=US"
+
 $TESTJAVA${FS}bin${FS}keytool ${TESTTOOLVMOPTS} -printcertreq -help 2> h1 || exit 1
 $TESTJAVA${FS}bin${FS}keytool ${TESTTOOLVMOPTS} -exportcert -help 2> h2 || exit 2
 
--- a/jdk/test/sun/security/tools/keytool/keyalg.sh	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/sun/security/tools/keytool/keyalg.sh	Wed Jul 05 22:05:22 2017 +0200
@@ -31,6 +31,8 @@
   TESTJAVA=`dirname $JAVAC_CMD`/..
 fi
 
+TESTTOOLVMOPTS="$TESTTOOLVMOPTS -J-Duser.language=en -J-Duser.country=US"
+
 KS=ks
 KEYTOOL="$TESTJAVA/bin/keytool ${TESTTOOLVMOPTS} -keystore ks -storepass changeit -keypass changeit"
 
--- a/jdk/test/sun/security/tools/keytool/newhelp.sh	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/sun/security/tools/keytool/newhelp.sh	Wed Jul 05 22:05:22 2017 +0200
@@ -42,7 +42,8 @@
     ;;
 esac
 
-LANG=C
+TESTTOOLVMOPTS="$TESTTOOLVMOPTS -J-Duser.language=en -J-Duser.country=US"
+
 $TESTJAVA${FS}bin${FS}keytool ${TESTTOOLVMOPTS} -help 2> h1 || exit 1
 $TESTJAVA${FS}bin${FS}keytool ${TESTTOOLVMOPTS} -help -list 2> h2 || exit 2
 
--- a/jdk/test/sun/security/tools/keytool/standard.sh	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/sun/security/tools/keytool/standard.sh	Wed Jul 05 22:05:22 2017 +0200
@@ -58,9 +58,9 @@
     ;;
 esac
 
-EXTRAOPTS="-XaddExports:java.base/sun.security.tools.keytool=ALL-UNNAMED \
- -XaddExports:java.base/sun.security.util=ALL-UNNAMED \
- -XaddExports:java.base/sun.security.x509=ALL-UNNAMED"
+EXTRAOPTS="--add-exports java.base/sun.security.tools.keytool=ALL-UNNAMED \
+ --add-exports java.base/sun.security.util=ALL-UNNAMED \
+ --add-exports java.base/sun.security.x509=ALL-UNNAMED"
 
 ${COMPILEJAVA}${FS}bin${FS}javac ${TESTJAVACOPTS} ${TESTTOOLVMOPTS} ${EXTRAOPTS} -d . -XDignore.symbol.file ${TESTSRC}${FS}KeyToolTest.java || exit 10
 
--- a/jdk/test/sun/security/validator/certreplace.sh	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/sun/security/validator/certreplace.sh	Wed Jul 05 22:05:22 2017 +0200
@@ -83,6 +83,6 @@
 
 # 5. Build and run test
 
-EXTRAOPTS="-XaddExports:java.base/sun.security.validator=ALL-UNNAMED"
+EXTRAOPTS="--add-exports java.base/sun.security.validator=ALL-UNNAMED"
 $JAVAC ${TESTJAVACOPTS} ${TESTTOOLVMOPTS} ${EXTRAOPTS} -d . ${TESTSRC}${FS}CertReplace.java
 $JAVA ${TESTVMOPTS} ${EXTRAOPTS} CertReplace certreplace.jks certreplace.certs
--- a/jdk/test/sun/security/validator/samedn.sh	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/sun/security/validator/samedn.sh	Wed Jul 05 22:05:22 2017 +0200
@@ -79,7 +79,7 @@
 # 5. Build and run test. Make sure the CA certs are ignored for validity check.
 # Check both, one of them might be dropped out of map in old codes.
 
-EXTRAOPTS="-XaddExports:java.base/sun.security.validator=ALL-UNNAMED"
+EXTRAOPTS="--add-exports java.base/sun.security.validator=ALL-UNNAMED"
 $JAVAC ${TESTJAVACOPTS} ${TESTTOOLVMOPTS} ${EXTRAOPTS} -d . ${TESTSRC}${FS}CertReplace.java
 $JAVA ${TESTVMOPTS} ${EXTRAOPTS} CertReplace samedn.jks samedn1.certs || exit 1
 $JAVA ${TESTVMOPTS} ${EXTRAOPTS} CertReplace samedn.jks samedn2.certs || exit 2
--- a/jdk/test/sun/text/IntHashtable/Bug4170614Test.sh	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/sun/text/IntHashtable/Bug4170614Test.sh	Wed Jul 05 22:05:22 2017 +0200
@@ -63,7 +63,7 @@
     -Xmodule:java.base \
     -d ${TEST_JAVABASE} Bug4170614Test.java
 
-${TESTJAVA}/bin/java ${TESTVMOPTS} -Xpatch:java.base=${TEST_JAVABASE} java.text.Bug4170614Test
+${TESTJAVA}/bin/java ${TESTVMOPTS} --patch-module java.base=${TEST_JAVABASE} java.text.Bug4170614Test
 
 result=$?
 
--- a/jdk/test/sun/tools/java/CFCTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/sun/tools/java/CFCTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -24,9 +24,11 @@
 /*
  * @test
  * @bug 8011805
- * @modules jdk.rmic/sun.tools.java jdk.rmic/sun.rmi.rmic
  * @summary Update sun.tools.java class file reading/writing support to include
  *   the new constant pool entries (including invokedynamic)
+ * @modules jdk.rmic/sun.rmi.rmic
+ *          jdk.rmic/sun.tools.java
+ * @run main CFCTest
  */
 
 import java.io.DataInputStream;
--- a/jdk/test/sun/util/locale/provider/Bug8038436.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/sun/util/locale/provider/Bug8038436.java	Wed Jul 05 22:05:22 2017 +0200
@@ -28,7 +28,7 @@
  * @modules java.base/sun.util.locale.provider
  *          java.base/sun.util.spi
  * @compile -XDignore.symbol.file Bug8038436.java
- * @run main/othervm  -limitmods java.base           Bug8038436  security
+ * @run main/othervm  --limit-modules java.base      Bug8038436  security
  * @run main/othervm  -Djava.locale.providers=COMPAT Bug8038436  availlocs
  */
 
@@ -69,7 +69,7 @@
 
         /*
          * Check only English/ROOT locales are returned if the jdk.localedata
-         * module is not loaded (implied by "-limitmods java.base").
+         * module is not loaded (implied by "--limit-modules java.base").
          */
         List<Locale> nonEnglishLocales= (Arrays.stream(Locale.getAvailableLocales())
                 .filter(l -> (l != Locale.ROOT && !(l.getLanguage() == "en" && (l.getCountry() == "US" || l.getCountry() == "" ))))
--- a/jdk/test/tools/jar/modularJar/Basic.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/tools/jar/modularJar/Basic.java	Wed Jul 05 22:05:22 2017 +0200
@@ -460,7 +460,7 @@
             "--no-manifest",
             "-C", barModInfo.toString(), "module-info.class")  // stuff in bar's info
             .assertSuccess();
-        jar("-p",
+        jar("-d",
             "--file=" + modularJar.toString())
             .assertSuccess()
             .resultChecker(r -> {
@@ -499,14 +499,14 @@
             "--file=" + modularJar.toString(),
             "--main-class=" + FOO.mainClass,
             "--module-version=" + FOO.version,
-            "--modulepath=" + mp.toString(),
+            "--module-path=" + mp.toString(),
             "--hash-modules=" + "bar",
             "--no-manifest",
             "-C", modClasses.toString(), ".")
             .assertSuccess();
 
         java(mp, BAR.moduleName + "/" + BAR.mainClass,
-             "-XaddExports:java.base/jdk.internal.module=bar")
+             "--add-exports", "java.base/jdk.internal.module=bar")
             .assertSuccess()
             .resultChecker(r -> {
                 assertModuleData(r, BAR);
@@ -535,7 +535,7 @@
             "--file=" + fooJar.toString(),
             "--main-class=" + FOO.mainClass,
             "--module-version=" + FOO.version,
-            "--modulepath=" + mp.toString(),
+            "-p", mp.toString(),  // test short-form
             "--hash-modules=" + "bar",
             "--no-manifest",
             "-C", fooClasses.toString(), ".").assertSuccess();
@@ -550,7 +550,7 @@
             "-C", barClasses.toString(), ".").assertSuccess();
 
         java(mp, BAR.moduleName + "/" + BAR.mainClass,
-             "-XaddExports:java.base/jdk.internal.module=bar")
+             "--add-exports", "java.base/jdk.internal.module=bar")
             .assertFailure()
             .resultChecker(r -> {
                 // Expect similar output: "java.lang.module.ResolutionException: Hash
@@ -684,7 +684,7 @@
             "-C", modClasses.toString(), ".")
             .assertSuccess();
 
-        for (String option : new String[]  {"--print-module-descriptor", "-p" }) {
+        for (String option : new String[]  {"--print-module-descriptor", "-d" }) {
             jar(option,
                 "--file=" + modularJar.toString())
                 .assertSuccess()
@@ -711,7 +711,7 @@
             "-C", modClasses.toString(), ".")
             .assertSuccess();
 
-        for (String option : new String[]  {"--print-module-descriptor", "-p" }) {
+        for (String option : new String[]  {"--print-module-descriptor", "-d" }) {
             jarWithStdin(modularJar.toFile(),
                          option)
                          .assertSuccess()
@@ -815,10 +815,12 @@
         }
         commands.add("-d");
         commands.add(dest.toString());
-        if (dest.toString().contains("bar"))
-            commands.add("-XaddExports:java.base/jdk.internal.module=bar");
+        if (dest.toString().contains("bar")) {
+            commands.add("--add-exports");
+            commands.add("java.base/jdk.internal.module=bar");
+        }
         if (modulePath != null) {
-            commands.add("-mp");
+            commands.add("--module-path");
             commands.add(modulePath.toString());
         }
         Stream.of(sourceFiles).map(Object::toString).forEach(x -> commands.add(x));
@@ -838,7 +840,7 @@
             commands.addAll(Arrays.asList(JAVA_OPTIONS.split("\\s+", -1)));
         }
         Stream.of(args).forEach(x -> commands.add(x));
-        commands.add("-mp");
+        commands.add("--module-path");
         commands.add(modulePath.toString());
         commands.add("-m");
         commands.add(entryPoint);
--- a/jdk/test/tools/jar/multiRelease/Basic.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/tools/jar/multiRelease/Basic.java	Wed Jul 05 22:05:22 2017 +0200
@@ -43,6 +43,7 @@
 import java.util.zip.*;
 
 import jdk.test.lib.JDKToolFinder;
+import jdk.test.lib.Utils;
 
 import static java.lang.String.format;
 import static java.lang.System.out;
@@ -199,6 +200,262 @@
     }
 
     /*
+     * The following tests exercise the jar validator
+     */
+
+    @Test
+    // META-INF/versions/9 class has different api than base class
+    public void test04() throws IOException {
+        String jarfile = "test.jar";
+
+        compile("test01");  //use same data as test01
+
+        Path classes = Paths.get("classes");
+
+        // replace the v9 class
+        Path source = Paths.get(src, "data", "test04", "v9", "version");
+        javac(classes.resolve("v9"), source.resolve("Version.java"));
+
+        jar("cf", jarfile, "-C", classes.resolve("base").toString(), ".",
+                "--release", "9", "-C", classes.resolve("v9").toString(), ".")
+                .assertFailure()
+                .resultChecker(r ->
+                    assertTrue(r.output.contains("different api from earlier"), r.output)
+                );
+
+        delete(jarfile);
+        deleteDir(Paths.get(usr, "classes"));
+    }
+
+    @Test
+    // META-INF/versions/9 contains an extra public class
+    public void test05() throws IOException {
+        String jarfile = "test.jar";
+
+        compile("test01");  //use same data as test01
+
+        Path classes = Paths.get("classes");
+
+        // add the new v9 class
+        Path source = Paths.get(src, "data", "test05", "v9", "version");
+        javac(classes.resolve("v9"), source.resolve("Extra.java"));
+
+        jar("cf", jarfile, "-C", classes.resolve("base").toString(), ".",
+                "--release", "9", "-C", classes.resolve("v9").toString(), ".")
+                .assertFailure()
+                .resultChecker(r ->
+                        assertTrue(r.output.contains("contains a new public class"), r.output)
+                );
+
+        delete(jarfile);
+        deleteDir(Paths.get(usr, "classes"));
+    }
+
+    @Test
+    // META-INF/versions/9 contains an extra package private class -- this is okay
+    public void test06() throws IOException {
+        String jarfile = "test.jar";
+
+        compile("test01");  //use same data as test01
+
+        Path classes = Paths.get("classes");
+
+        // add the new v9 class
+        Path source = Paths.get(src, "data", "test06", "v9", "version");
+        javac(classes.resolve("v9"), source.resolve("Extra.java"));
+
+        jar("cf", jarfile, "-C", classes.resolve("base").toString(), ".",
+                "--release", "9", "-C", classes.resolve("v9").toString(), ".")
+                .assertSuccess();
+
+        delete(jarfile);
+        deleteDir(Paths.get(usr, "classes"));
+    }
+
+    @Test
+    // META-INF/versions/9 contains an identical class to base entry class
+    // this is okay but produces warning
+    public void test07() throws IOException {
+        String jarfile = "test.jar";
+
+        compile("test01");  //use same data as test01
+
+        Path classes = Paths.get("classes");
+
+        // add the new v9 class
+        Path source = Paths.get(src, "data", "test01", "base", "version");
+        javac(classes.resolve("v9"), source.resolve("Version.java"));
+
+        jar("cf", jarfile, "-C", classes.resolve("base").toString(), ".",
+                "--release", "9", "-C", classes.resolve("v9").toString(), ".")
+                .assertSuccess()
+                .resultChecker(r ->
+                        assertTrue(r.output.contains("contains a class that is identical"), r.output)
+                );
+
+        delete(jarfile);
+        deleteDir(Paths.get(usr, "classes"));
+    }
+
+    @Test
+    // resources with same name in different versions
+    // this is okay but produces warning
+    public void test08() throws IOException {
+        String jarfile = "test.jar";
+
+        compile("test01");  //use same data as test01
+
+        Path classes = Paths.get("classes");
+
+        // add a resource to the base
+        Path source = Paths.get(src, "data", "test01", "base", "version");
+        Files.copy(source.resolve("Version.java"), classes.resolve("base")
+                .resolve("version").resolve("Version.java"));
+
+        jar("cf", jarfile, "-C", classes.resolve("base").toString(), ".",
+                "--release", "9", "-C", classes.resolve("v9").toString(), ".")
+                .assertSuccess()
+                .resultChecker(r ->
+                        assertTrue(r.output.isEmpty(), r.output)
+                );
+
+        // now add a different resource with same name to META-INF/version/9
+        Files.copy(source.resolve("Main.java"), classes.resolve("v9")
+                .resolve("version").resolve("Version.java"));
+
+        jar("cf", jarfile, "-C", classes.resolve("base").toString(), ".",
+                "--release", "9", "-C", classes.resolve("v9").toString(), ".")
+                .assertSuccess()
+                .resultChecker(r ->
+                        assertTrue(r.output.contains("multiple resources with same name"), r.output)
+                );
+
+        delete(jarfile);
+        deleteDir(Paths.get(usr, "classes"));
+    }
+
+    @Test
+    // a class with an internal name different from the external name
+    public void test09() throws IOException {
+        String jarfile = "test.jar";
+
+        compile("test01");  //use same data as test01
+
+        Path classes = Paths.get("classes");
+
+        Path base = classes.resolve("base").resolve("version");
+
+        Files.copy(base.resolve("Main.class"), base.resolve("Foo.class"));
+
+        jar("cf", jarfile, "-C", classes.resolve("base").toString(), ".",
+                "--release", "9", "-C", classes.resolve("v9").toString(), ".")
+                .assertFailure()
+                .resultChecker(r ->
+                        assertTrue(r.output.contains("names do not match"), r.output)
+                );
+
+        delete(jarfile);
+        deleteDir(Paths.get(usr, "classes"));
+    }
+
+    @Test
+    // assure that basic nested classes are acceptable
+    public void test10() throws IOException {
+        String jarfile = "test.jar";
+
+        compile("test01");  //use same data as test01
+
+        Path classes = Paths.get("classes");
+
+        // add a base class with a nested class
+        Path source = Paths.get(src, "data", "test10", "base", "version");
+        javac(classes.resolve("base"), source.resolve("Nested.java"));
+
+        // add a versioned class with a nested class
+        source = Paths.get(src, "data", "test10", "v9", "version");
+        javac(classes.resolve("v9"), source.resolve("Nested.java"));
+
+        jar("cf", jarfile, "-C", classes.resolve("base").toString(), ".",
+                "--release", "9", "-C", classes.resolve("v9").toString(), ".")
+                .assertSuccess();
+
+        delete(jarfile);
+        deleteDir(Paths.get(usr, "classes"));
+    }
+
+    @Test
+    // a base entry contains a nested class that doesn't have a matching top level class
+    public void test11() throws IOException {
+        String jarfile = "test.jar";
+
+        compile("test01");  //use same data as test01
+
+        Path classes = Paths.get("classes");
+
+        // add a base class with a nested class
+        Path source = Paths.get(src, "data", "test10", "base", "version");
+        javac(classes.resolve("base"), source.resolve("Nested.java"));
+
+        // remove the top level class, thus isolating the nested class
+        Files.delete(classes.resolve("base").resolve("version").resolve("Nested.class"));
+
+        // add a versioned class with a nested class
+        source = Paths.get(src, "data", "test10", "v9", "version");
+        javac(classes.resolve("v9"), source.resolve("Nested.java"));
+
+        jar("cf", jarfile, "-C", classes.resolve("base").toString(), ".",
+                "--release", "9", "-C", classes.resolve("v9").toString(), ".")
+                .assertFailure()
+                .resultChecker(r -> {
+                    String[] msg = r.output.split("\\R");
+                    // There should be 3 error messages, cascading from the first.  Once we
+                    // remove the base top level class, the base nested class becomes isolated,
+                    // also the versioned top level class becomes a new public class, thus ignored
+                    // for subsequent checks, leading to the associated versioned nested class
+                    // becoming an isolated nested class
+                    assertTrue(msg.length == 4);
+                    assertTrue(msg[0].contains("an isolated nested class"), msg[0]);
+                    assertTrue(msg[1].contains("contains a new public class"), msg[1]);
+                    assertTrue(msg[2].contains("an isolated nested class"), msg[2]);
+                    assertTrue(msg[3].contains("invalid multi-release jar file"), msg[3]);
+                });
+
+        delete(jarfile);
+        deleteDir(Paths.get(usr, "classes"));
+    }
+
+    @Test
+    // a versioned entry contains a nested class that doesn't have a matching top level class
+    public void test12() throws IOException {
+        String jarfile = "test.jar";
+
+        compile("test01");  //use same data as test01
+
+        Path classes = Paths.get("classes");
+
+        // add a base class with a nested class
+        Path source = Paths.get(src, "data", "test10", "base", "version");
+        javac(classes.resolve("base"), source.resolve("Nested.java"));
+
+        // add a versioned class with a nested class
+        source = Paths.get(src, "data", "test10", "v9", "version");
+        javac(classes.resolve("v9"), source.resolve("Nested.java"));
+
+        // remove the top level class, thus isolating the nested class
+        Files.delete(classes.resolve("v9").resolve("version").resolve("Nested.class"));
+
+        jar("cf", jarfile, "-C", classes.resolve("base").toString(), ".",
+                "--release", "9", "-C", classes.resolve("v9").toString(), ".")
+                .assertFailure()
+                .resultChecker(r ->
+                        assertTrue(r.output.contains("an isolated nested class"), r.output)
+                );
+
+        delete(jarfile);
+        deleteDir(Paths.get(usr, "classes"));
+    }
+
+    /*
      *  Test Infrastructure
      */
     private void compile(String test) throws IOException {
@@ -243,7 +500,7 @@
     }
 
     private void delete(String name) throws IOException {
-        Files.delete(Paths.get(usr, name));
+        Files.deleteIfExists(Paths.get(usr, name));
     }
 
     private void deleteDir(Path dir) throws IOException {
@@ -271,6 +528,10 @@
 
         List<String> commands = new ArrayList<>();
         commands.add(javac);
+        String opts = System.getProperty("test.compiler.opts");
+        if (!opts.isEmpty()) {
+            commands.addAll(Arrays.asList(opts.split(" +")));
+        }
         commands.add("-d");
         commands.add(dest.toString());
         Stream.of(sourceFiles).map(Object::toString).forEach(x -> commands.add(x));
@@ -282,6 +543,7 @@
         String jar = JDKToolFinder.getJDKTool("jar");
         List<String> commands = new ArrayList<>();
         commands.add(jar);
+        commands.addAll(Utils.getForwardVmOptions());
         Stream.of(args).forEach(x -> commands.add(x));
         ProcessBuilder p = new ProcessBuilder(commands);
         if (stdinSource != null)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/tools/jar/multiRelease/data/test04/v9/version/Version.java	Wed Jul 05 22:05:22 2017 +0200
@@ -0,0 +1,14 @@
+package version;
+
+public class Version {
+    public int getVersion() {
+        return 9;
+    }
+
+    protected void doNothing() {
+    }
+
+    // extra publc method
+    public void anyName() {
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/tools/jar/multiRelease/data/test05/v9/version/Extra.java	Wed Jul 05 22:05:22 2017 +0200
@@ -0,0 +1,13 @@
+package version;
+
+public class Extra {
+    public int getVersion() {
+        return 9;
+    }
+
+    protected void doNothing() {
+    }
+
+    private void anyName() {
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/tools/jar/multiRelease/data/test06/v9/version/Extra.java	Wed Jul 05 22:05:22 2017 +0200
@@ -0,0 +1,13 @@
+package version;
+
+class Extra {
+    public int getVersion() {
+        return 9;
+    }
+
+    protected void doNothing() {
+    }
+
+    private void anyName() {
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/tools/jar/multiRelease/data/test10/base/version/Nested.java	Wed Jul 05 22:05:22 2017 +0200
@@ -0,0 +1,17 @@
+package version;
+
+public class Nested {
+    public int getVersion() {
+        return 9;
+    }
+
+    protected void doNothing() {
+    }
+
+    private void anyName() {
+    }
+
+    class nested {
+        int save;
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/tools/jar/multiRelease/data/test10/v9/version/Nested.java	Wed Jul 05 22:05:22 2017 +0200
@@ -0,0 +1,14 @@
+package version;
+
+public class Nested {
+    public int getVersion() {
+        return 9;
+    }
+
+    protected void doNothing() {
+    }
+
+    class nested {
+        int save = getVersion();
+    }
+}
--- a/jdk/test/tools/jimage/VerifyJimage.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/tools/jimage/VerifyJimage.java	Wed Jul 05 22:05:22 2017 +0200
@@ -49,7 +49,7 @@
  * @test
  * @summary Verify jimage
  * @modules java.base/jdk.internal.jimage
- * @run main/othervm -Djdk.launcher.addmods=ALL-SYSTEM VerifyJimage
+ * @run main/othervm --add-modules=ALL-SYSTEM VerifyJimage
  */
 
 /**
--- a/jdk/test/tools/jlink/CustomPluginTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/tools/jlink/CustomPluginTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -93,7 +93,8 @@
         String name = "customplugin";
         Path src = Paths.get(System.getProperty("test.src")).resolve(name);
         Path classes = helper.getJmodClassesDir().resolve(name);
-        JImageGenerator.compile(src, classes, "-XaddExports:jdk.jlink/jdk.tools.jlink.internal=customplugin");
+        JImageGenerator.compile(src, classes,
+                                "--add-exports", "jdk.jlink/jdk.tools.jlink.internal=customplugin");
         return JImageGenerator.getJModTask()
                 .addClassPath(classes)
                 .jmod(helper.getJmodDir().resolve(name + ".jmod"))
--- a/jdk/test/tools/jlink/JLinkNegativeTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/tools/jlink/JLinkNegativeTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -95,7 +95,7 @@
     }
 
     public void testNotExistInAddMods() {
-        // cannot find jmod from --addmods
+        // cannot find jmod from --add-modules
         JImageGenerator.getJLinkTask()
                 .modulePath(".")
                 .addMods("not_exist")
--- a/jdk/test/tools/jlink/JLinkTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/tools/jlink/JLinkTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -118,7 +118,7 @@
                     .output(helper.createNewImageDir(moduleName))
                     .addMods("leaf1")
                     .option("")
-                    .call().assertFailure("Error: no value given for --modulepath");
+                    .call().assertFailure("Error: no value given for --module-path");
         }
 
         {
@@ -250,7 +250,7 @@
         // @file
         {
             Path path = Paths.get("embedded.properties");
-            Files.write(path, Collections.singletonList("--strip-debug --addmods " +
+            Files.write(path, Collections.singletonList("--strip-debug --add-modules " +
                     "toto.unknown --compress UNKNOWN\n"));
             String[] userOptions = {"@", path.toAbsolutePath().toString()};
             String moduleName = "configembeddednocompresscomposite2";
--- a/jdk/test/tools/jlink/basic/BasicTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/tools/jlink/basic/BasicTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -106,8 +106,8 @@
     private void runJlink(Path image, String modName, String... options) {
         List<String> args = new ArrayList<>();
         Collections.addAll(args,
-                "--modulepath", jdkMods + File.pathSeparator + jmods,
-                "--addmods", modName,
+                "--module-path", jdkMods + File.pathSeparator + jmods,
+                "--add-modules", modName,
                 "--output", image.toString());
         Collections.addAll(args, options);
         int rc = jdk.tools.jlink.internal.Main.run(args.toArray(new String[args.size()]), new PrintWriter(System.out));
--- a/jdk/test/tools/jlink/plugins/SystemModuleDescriptors/UserModuleTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/tools/jlink/plugins/SystemModuleDescriptors/UserModuleTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -73,7 +73,7 @@
 
         for (String mn : modules) {
             Path msrc = SRC_DIR.resolve(mn);
-            assertTrue(CompilerUtils.compile(msrc, MODS_DIR, "-modulesourcepath", SRC_DIR.toString()));
+            assertTrue(CompilerUtils.compile(msrc, MODS_DIR, "--module-source-path", SRC_DIR.toString()));
         }
 
         if (Files.exists(IMAGE)) {
@@ -87,8 +87,8 @@
         Path jlink = Paths.get(JAVA_HOME, "bin", "jlink");
         String mp = JMODS.toString() + File.pathSeparator + MODS_DIR.toString();
         assertTrue(executeProcess(jlink.toString(), "--output", outputDir.toString(),
-                        "--addmods", Arrays.stream(modules).collect(Collectors.joining(",")),
-                        "--modulepath", mp)
+                        "--add-modules", Arrays.stream(modules).collect(Collectors.joining(",")),
+                        "--module-path", mp)
                         .outputTo(System.out)
                         .errorTo(System.out)
                         .getExitValue() == 0);
--- a/jdk/test/tools/jmod/JmodNegativeTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/tools/jmod/JmodNegativeTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -314,7 +314,7 @@
         jmod("create",
              "--class-path", cp,
              "--hash-modules", ".*",
-             "--modulepath", emptyDir.toString(),
+             "--module-path", emptyDir.toString(),
             jmod.toString())
             .resultChecker(r ->
                 assertContains(r.output, "No hashes recorded: " +
@@ -335,7 +335,7 @@
             jmod("create",
                  "--class-path", cp,
                  "--hash-modules", ".*",
-                 "--modulepath", MODS_DIR.toString(),
+                 "--module-path", MODS_DIR.toString(),
                  jmod.toString())
                 .assertFailure();
         } finally {
@@ -353,7 +353,7 @@
 
         jmod("create",
              "--hash-modules", ".*",
-             "--modulepath", file.toString(),
+             "--module-path", file.toString(),
              jmod.toString())
             .assertFailure()
             .resultChecker(r ->
@@ -370,7 +370,7 @@
         List<Supplier<JmodResult>> tasks = Arrays.asList(
                 () -> jmod("create",
                            "--hash-modules", "anyPattern",
-                           "--modulepath", "doesNotExist",
+                           "--module-path", "doesNotExist",
                            "output.jmod"),
                 () -> jmod("create",
                            "--class-path", "doesNotExist",
@@ -418,7 +418,7 @@
         List<Supplier<JmodResult>> tasks = Arrays.asList(
             () -> jmod("create",
                        "--hash-modules", "anyPattern",
-                       "--modulepath","empty" + pathSeparator + "doesNotExist",
+                       "--module-path","empty" + pathSeparator + "doesNotExist",
                        "output.jmod"),
             () -> jmod("create",
                        "--class-path", "empty" + pathSeparator + "doesNotExist",
@@ -467,7 +467,7 @@
                            "--class-path", "aFile.txt",
                            "output.jmod"),
                 () -> jmod("create",
-                           "--modulepath", "aFile.txt",
+                           "--module-path", "aFile.txt",
                            "output.jmod"),
                 () -> jmod("create",
                            "--cmds", "aFile.txt",
--- a/jdk/test/tools/jmod/hashes/HashesTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/tools/jmod/hashes/HashesTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -1,5 +1,5 @@
 /**
- * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -88,7 +88,7 @@
         // build m1
         compileModule("m1", modSrc);
         // no hash is recorded since m1 has outgoing edges
-        jmod("m1", "--modulepath", jmods.toString(), "--hash-modules", ".*");
+        jmod("m1", "--module-path", jmods.toString(), "--hash-modules", ".*");
 
         // compile org.bar and org.foo
         compileModule("org.bar", modSrc);
@@ -109,17 +109,17 @@
         }
 
         // hash m1 in m2
-        jmod("m2", "--modulepath", jmods.toString(), "--hash-modules", "m1");
+        jmod("m2", "--module-path", jmods.toString(), "--hash-modules", "m1");
         checkHashes(hashes("m2").get(), "m1");
 
         // hash m1 in m2
-        jmod("m2", "--modulepath", jmods.toString(), "--hash-modules", ".*");
+        jmod("m2", "--module-path", jmods.toString(), "--hash-modules", ".*");
         checkHashes(hashes("m2").get(), "m1");
 
         // create m2.jmod with no hash
         jmod("m2");
         // run jmod hash command to hash m1 in m2 and m3
-        runJmod(Arrays.asList("hash", "--modulepath", jmods.toString(),
+        runJmod(Arrays.asList("hash", "--module-path", jmods.toString(),
                 "--hash-modules", ".*"));
         checkHashes(hashes("m2").get(), "m1");
         checkHashes(hashes("m3").get(), "m1");
@@ -127,10 +127,10 @@
         jmod("org.bar");
         jmod("org.foo");
 
-        jmod("org.bar", "--modulepath", jmods.toString(), "--hash-modules", "org.*");
+        jmod("org.bar", "--module-path", jmods.toString(), "--hash-modules", "org.*");
         checkHashes(hashes("org.bar").get(), "org.foo");
 
-        jmod("m3", "--modulepath", jmods.toString(), "--hash-modules", ".*");
+        jmod("m3", "--module-path", jmods.toString(), "--hash-modules", ".*");
         checkHashes(hashes("m3").get(), "org.foo", "org.bar", "m1");
     }
 
@@ -185,7 +185,7 @@
 
     private void compileModule(String moduleName, Path src) throws IOException {
         Path msrc = src.resolve(moduleName);
-        assertTrue(CompilerUtils.compile(msrc, mods, "-modulesourcepath", src.toString()));
+        assertTrue(CompilerUtils.compile(msrc, mods, "--module-source-path", src.toString()));
     }
 
     private void jmod(String moduleName, String... options) throws IOException {
--- a/jdk/test/tools/launcher/MiscTests.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/tools/launcher/MiscTests.java	Wed Jul 05 22:05:22 2017 +0200
@@ -70,7 +70,7 @@
 
         final String mainClass = "Foo6856415";
         final String exportOpts
-            = "-XaddExports:jdk.crypto.pkcs11/sun.security.pkcs11=ALL-UNNAMED";
+            = "--add-exports=jdk.crypto.pkcs11/sun.security.pkcs11=ALL-UNNAMED";
 
         List<String> scratch = new ArrayList<>();
         scratch.add("public class Foo6856415 {");
--- a/jdk/test/tools/launcher/ToolsOpts.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/tools/launcher/ToolsOpts.java	Wed Jul 05 22:05:22 2017 +0200
@@ -151,7 +151,7 @@
         init();
         TestResult tr;
         int jpos = -1;
-        String xPatch = "-J-Xpatch:jdk.compiler=jdk.compiler";
+        String xPatch = "-J--patch-module=jdk.compiler=jdk.compiler";
         for (String arg[] : optionPatterns) {
             jpos = indexOfJoption(arg);
             //Build a cmd string for output in results reporting.
--- a/jdk/test/tools/launcher/modules/addexports/AddExportsTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/tools/launcher/modules/addexports/AddExportsTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -27,7 +27,7 @@
  * @modules jdk.compiler
  * @build AddExportsTest CompilerUtils jdk.testlibrary.*
  * @run testng AddExportsTest
- * @summary Basic tests for java -XaddExports
+ * @summary Basic tests for java --add-exports
  */
 
 import java.nio.file.Path;
@@ -71,7 +71,7 @@
         boolean compiled = CompilerUtils.compile(
                 SRC_DIR.resolve(TEST1_MODULE),
                 MODS_DIR.resolve(TEST1_MODULE),
-                "-XaddExports:java.base/jdk.internal.misc=m1");
+                "--add-exports", "java.base/jdk.internal.misc=m1");
         assertTrue(compiled, "module " + TEST1_MODULE + " did not compile");
 
         // javac -d upgrademods/java.transaction src/java.transaction/**
@@ -80,12 +80,12 @@
                 UPGRADE_MODS_DIRS.resolve("java.transaction"));
         assertTrue(compiled, "module java.transaction did not compile");
 
-        // javac -upgrademodulepath upgrademods -d mods/m2 src/m2/**
+        // javac --upgrade-module-path upgrademods -d mods/m2 src/m2/**
         compiled = CompilerUtils.compile(
                 SRC_DIR.resolve(TEST2_MODULE),
                 MODS_DIR.resolve(TEST2_MODULE),
-                "-upgrademodulepath", UPGRADE_MODS_DIRS.toString(),
-                "-XaddExports:java.transaction/javax.transaction.internal=m2");
+                "--upgrade-module-path", UPGRADE_MODS_DIRS.toString(),
+                "--add-exports", "java.transaction/javax.transaction.internal=m2");
         assertTrue(compiled, "module " + TEST2_MODULE + " did not compile");
 
         // javac -d mods/m3 src/m3/**
@@ -107,7 +107,7 @@
     public void testSanity() throws Exception {
 
         int exitValue
-            =  executeTestJava("-XaddExports:java.base/jdk.internal.reflect=ALL-UNNAMED",
+            =  executeTestJava("--add-exports", "java.base/jdk.internal.reflect=ALL-UNNAMED",
                                "-version")
                 .outputTo(System.out)
                 .errorTo(System.out)
@@ -122,12 +122,12 @@
      */
     public void testUnnamedModule() throws Exception {
 
-        // java -XaddExports:java.base/jdk.internal.misc=ALL-UNNAMED \
+        // java --add-exports java.base/jdk.internal.misc=ALL-UNNAMED \
         //      -cp mods/$TESTMODULE jdk.test.UsesUnsafe
 
         String classpath = MODS_DIR.resolve(TEST1_MODULE).toString();
         int exitValue
-            = executeTestJava("-XaddExports:java.base/jdk.internal.misc=ALL-UNNAMED",
+            = executeTestJava("--add-exports", "java.base/jdk.internal.misc=ALL-UNNAMED",
                               "-cp", classpath,
                               TEST1_MAIN_CLASS)
                 .outputTo(System.out)
@@ -143,13 +143,13 @@
      */
     public void testNamedModule() throws Exception {
 
-        //  java -XaddExports:java.base/jdk.internal.misc=test \
-        //       -mp mods -m $TESTMODULE/$MAIN_CLASS
+        //  java --add-exports java.base/jdk.internal.misc=test \
+        //       --module-path mods -m $TESTMODULE/$MAIN_CLASS
 
         String mid = TEST1_MODULE + "/" + TEST1_MAIN_CLASS;
         int exitValue =
-            executeTestJava("-XaddExports:java.base/jdk.internal.misc=" + TEST1_MODULE,
-                            "-mp", MODS_DIR.toString(),
+            executeTestJava("--add-exports", "java.base/jdk.internal.misc=" + TEST1_MODULE,
+                            "--module-path", MODS_DIR.toString(),
                             "-m", mid)
                 .outputTo(System.out)
                 .errorTo(System.out)
@@ -160,17 +160,17 @@
 
 
     /**
-     * Test -XaddExports with upgraded module
+     * Test --add-exports with upgraded module
      */
     public void testWithUpgradedModule() throws Exception {
 
-        // java -XaddExports:java.transaction/javax.transaction.internal=m2
-        //      -upgrademodulepath upgrademods -mp mods -m ...
+        // java --add-exports java.transaction/javax.transaction.internal=m2
+        //      --upgrade-module-path upgrademods --module-path mods -m ...
         String mid = TEST2_MODULE + "/" + TEST2_MAIN_CLASS;
         int exitValue = executeTestJava(
-                "-XaddExports:java.transaction/javax.transaction.internal=m2",
-                "-upgrademodulepath", UPGRADE_MODS_DIRS.toString(),
-                "-mp", MODS_DIR.toString(),
+                "--add-exports", "java.transaction/javax.transaction.internal=m2",
+                "--upgrade-module-path", UPGRADE_MODS_DIRS.toString(),
+                "--module-path", MODS_DIR.toString(),
                 "-m", mid)
                 .outputTo(System.out)
                 .errorTo(System.out)
@@ -181,17 +181,17 @@
 
 
     /**
-     * Test -XaddExports with module that is added to the set of root modules
-     * with -addmods.
+     * Test --add-exports with module that is added to the set of root modules
+     * with --add-modules.
      */
     public void testWithAddMods() throws Exception {
 
-        // java -XaddExports:m4/jdk.test4=m3 -mp mods -m ...
+        // java --add-exports m4/jdk.test4=m3 --module-path mods -m ...
         String mid = TEST3_MODULE + "/" + TEST3_MAIN_CLASS;
         int exitValue = executeTestJava(
-                "-XaddExports:m4/jdk.test4=m3",
-                "-mp", MODS_DIR.toString(),
-                "-addmods", TEST4_MODULE,
+                "--add-exports", "m4/jdk.test4=m3",
+                "--module-path", MODS_DIR.toString(),
+                "--add-modules", TEST4_MODULE,
                 "-m", mid)
                 .outputTo(System.out)
                 .errorTo(System.out)
@@ -202,13 +202,13 @@
 
 
     /**
-     * -XaddExports can only be specified once
+     * --add-exports can only be specified once
      */
     public void testWithDuplicateOption() throws Exception {
 
         int exitValue
-            =  executeTestJava("-XaddExports:java.base/jdk.internal.reflect=ALL-UNNAMED",
-                               "-XaddExports:java.base/jdk.internal.reflect=ALL-UNNAMED",
+            =  executeTestJava("--add-exports", "java.base/jdk.internal.reflect=ALL-UNNAMED",
+                               "--add-exports", "java.base/jdk.internal.reflect=ALL-UNNAMED",
                                "-version")
                 .outputTo(System.out)
                 .errorTo(System.out)
@@ -220,14 +220,14 @@
 
 
     /**
-     * Exercise -XaddExports with bad values
+     * Exercise --add-exports with bad values
      */
     @Test(dataProvider = "badvalues")
     public void testWithBadValue(String value, String ignore) throws Exception {
 
-        //  -XaddExports:$VALUE -version
+        //  --add-exports $VALUE -version
         int exitValue =
-            executeTestJava("-XaddExports:" + value,
+            executeTestJava("--add-exports", value,
                             "-version")
                 .outputTo(System.out)
                 .errorTo(System.out)
--- a/jdk/test/tools/launcher/modules/addmods/AddModsTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/tools/launcher/modules/addmods/AddModsTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -28,7 +28,7 @@
  *          jdk.compiler
  * @build AddModsTest CompilerUtils jdk.testlibrary.*
  * @run testng AddModsTest
- * @summary Basic test for java -addmods
+ * @summary Basic test for java --add-modules
  */
 
 import java.nio.file.Path;
@@ -78,15 +78,15 @@
 
 
     /**
-     * Basic test of -addmods ALL-DEFAULT. Module java.sql should be
+     * Basic test of --add-modules ALL-DEFAULT. Module java.sql should be
      * resolved and the types in that module should be visible.
      */
     public void testAddDefaultModules1() throws Exception {
 
-        // java -addmods ALL-DEFAULT -mp mods1 -m test ...
+        // java --add-modules ALL-DEFAULT --module-path mods1 -m test ...
         int exitValue
-            = executeTestJava("-mp", MODS1_DIR.toString(),
-                              "-addmods", "ALL-DEFAULT",
+            = executeTestJava("--module-path", MODS1_DIR.toString(),
+                              "--add-modules", "ALL-DEFAULT",
                               "-m", TEST_MID,
                               "java.sql.Connection")
                 .outputTo(System.out)
@@ -97,16 +97,16 @@
     }
 
     /**
-     * Basic test of -addmods ALL-DEFAULT. Module java.annotations.common
+     * Basic test of --add-modules ALL-DEFAULT. Module java.annotations.common
      * should not resolved and so the types in that module should not be
      * visible.
      */
     public void testAddDefaultModules2() throws Exception {
 
-        // java -addmods ALL-DEFAULT -mp mods1 -m test ...
+        // java --add-modules ALL-DEFAULT --module-path mods1 -m test ...
         int exitValue
-            = executeTestJava("-mp", MODS1_DIR.toString(),
-                              "-addmods", "ALL-DEFAULT",
+            = executeTestJava("--module-path", MODS1_DIR.toString(),
+                              "--add-modules", "ALL-DEFAULT",
                               "-m", TEST_MID,
                               "javax.annotation.Generated")
                 .outputTo(System.out)
@@ -118,15 +118,15 @@
     }
 
     /**
-     * Basic test of -addmods ALL-SYSTEM. All system modules should be resolved
+     * Basic test of --add-modules ALL-SYSTEM. All system modules should be resolved
      * and thus all types in those modules should be visible.
      */
     public void testAddSystemModules() throws Exception {
 
-        // java -addmods ALL-SYSTEM -mp mods1 -m test ...
+        // java --add-modules ALL-SYSTEM --module-path mods1 -m test ...
         int exitValue
-            = executeTestJava("-mp", MODS1_DIR.toString(),
-                              "-addmods", "ALL-SYSTEM",
+            = executeTestJava("--module-path", MODS1_DIR.toString(),
+                              "--add-modules", "ALL-SYSTEM",
                               "-m", TEST_MID,
                               "java.sql.Connection",
                               "javax.annotation.Generated")
@@ -140,16 +140,16 @@
 
     /**
      * Run test on class path to load a type in a module on the application
-     * module path, uses {@code -addmods logger}.
+     * module path, uses {@code --add-modules logger}.
      */
     public void testRunWithAddMods() throws Exception {
 
-        // java -mp mods -addmods logger -cp classes test.Main
+        // java --module-path mods --add-modules logger -cp classes test.Main
         String classpath = MODS1_DIR.resolve(TEST_MODULE).toString();
         String modulepath = MODS2_DIR.toString();
         int exitValue
-            = executeTestJava("-mp", modulepath,
-                              "-addmods", LOGGER_MODULE,
+            = executeTestJava("--module-path", modulepath,
+                              "--add-modules", LOGGER_MODULE,
                               "-cp", classpath,
                               TEST_MAIN_CLASS,
                               "logger.Logger")
@@ -162,16 +162,16 @@
 
      /**
       * Run application on class path that makes use of module on the
-      * application module path. Does not use -addmods and so should
+      * application module path. Does not use --add-modules and so should
       * fail at run-time.
       */
      public void testRunMissingAddMods() throws Exception {
 
-         // java -mp mods -cp classes test.Main
+         // java --module-path mods -cp classes test.Main
          String classpath = MODS1_DIR.resolve(TEST_MODULE).toString();
          String modulepath = MODS1_DIR.toString();
          int exitValue
-             = executeTestJava("-mp", modulepath,
+             = executeTestJava("--module-path", modulepath,
                                "-cp", classpath,
                                TEST_MAIN_CLASS,
                                "logger.Logger")
@@ -186,16 +186,16 @@
 
     /**
      * Run test on class path to load a type in a module on the application
-     * module path, uses {@code -addmods ALL-MODULE-PATH}.
+     * module path, uses {@code --add-modules ALL-MODULE-PATH}.
      */
     public void testAddAllModulePath() throws Exception {
 
-        // java -mp mods -addmods ALL-MODULE-PATH -cp classes test.Main
+        // java --module-path mods --add-modules ALL-MODULE-PATH -cp classes test.Main
         String classpath = MODS1_DIR.resolve(TEST_MODULE).toString();
         String modulepath = MODS1_DIR.toString();
         int exitValue
-            = executeTestJava("-mp", modulepath,
-                              "-addmods", "ALL-MODULE-PATH",
+            = executeTestJava("--module-path", modulepath,
+                              "--add-modules", "ALL-MODULE-PATH",
                               "-cp", classpath,
                               TEST_MAIN_CLASS)
                 .outputTo(System.out)
@@ -207,13 +207,13 @@
 
 
     /**
-     * Test {@code -addmods ALL-MODULE-PATH} without {@code -modulepath}.
+     * Test {@code --add-modules ALL-MODULE-PATH} without {@code --module-path}.
      */
     public void testAddAllModulePathWithNoModulePath() throws Exception {
 
-        // java -addmods ALL-MODULE-PATH -version
+        // java --add-modules ALL-MODULE-PATH -version
         int exitValue
-            = executeTestJava("-addmods", "ALL-MODULE-PATH",
+            = executeTestJava("--add-modules", "ALL-MODULE-PATH",
                               "-version")
                 .outputTo(System.out)
                 .errorTo(System.out)
@@ -224,14 +224,14 @@
 
 
     /**
-     * Attempt to run with a bad module name specified to -addmods
+     * Attempt to run with a bad module name specified to --add-modules
      */
     public void testRunWithBadAddMods() throws Exception {
 
-        // java -mp mods -addmods DoesNotExist -m test ...
+        // java --module-path mods --add-modules DoesNotExist -m test ...
         int exitValue
-            = executeTestJava("-mp", MODS1_DIR.toString(),
-                              "-addmods", "DoesNotExist",
+            = executeTestJava("--module-path", MODS1_DIR.toString(),
+                              "--add-modules", "DoesNotExist",
                               "-m", TEST_MID)
                 .outputTo(System.out)
                 .errorTo(System.out)
--- a/jdk/test/tools/launcher/modules/addmods/src/logger/logger/Logger.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/tools/launcher/modules/addmods/src/logger/logger/Logger.java	Wed Jul 05 22:05:22 2017 +0200
@@ -24,7 +24,7 @@
 package logger;
 
 /**
- * No-op user module for use by the {@code java -addmods} tests.
+ * No-op user module for use by the {@code java --add-modules} tests.
  */
 public class Logger {
 }
--- a/jdk/test/tools/launcher/modules/addmods/src/test/test/Main.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/tools/launcher/modules/addmods/src/test/test/Main.java	Wed Jul 05 22:05:22 2017 +0200
@@ -24,7 +24,7 @@
 package test;
 
 /**
- * Invoked by tests for the {@code java -addmods} option to check that types
+ * Invoked by tests for the {@code java --add-modules} option to check that types
  * are visible.
  */
 public class Main {
--- a/jdk/test/tools/launcher/modules/addreads/AddReadsTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/tools/launcher/modules/addreads/AddReadsTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -27,7 +27,7 @@
  * @modules jdk.compiler
  * @build AddReadsTest CompilerUtils JarUtils jdk.testlibrary.*
  * @run testng AddReadsTest
- * @summary Basic tests for java -XaddReads
+ * @summary Basic tests for java --add-reads
  */
 
 import java.nio.file.Path;
@@ -45,7 +45,7 @@
  * The tests consists of two modules: m1 and junit.
  * Code in module m1 calls into code in module junit but the module-info.java
  * does not have a 'requires'. Instead a read edge is added via the command
- * line option -XaddReads.
+ * line option --add-reads.
  */
 
 @Test
@@ -72,7 +72,7 @@
             .compile(SRC_DIR.resolve("m1"),
                     MODS_DIR.resolve("m1"),
                     "-cp", CLASSES_DIR.toString(),
-                    "-XaddReads:m1=ALL-UNNAMED"));
+                    "--add-reads", "m1=ALL-UNNAMED"));
 
         // jar cf mods/junit.jar -C classes .
         JarUtils.createJarFile(MODS_DIR.resolve("junit.jar"), CLASSES_DIR);
@@ -91,11 +91,11 @@
      */
     public void testJUnitOnModulePath() throws Exception {
 
-        // java -mp mods -addmods junit -XaddReads:m1=junit -m ..
+        // java --module-path mods --add-modules junit --add-reads m1=junit -m ..
         int exitValue
-            = run("-mp", MODS_DIR.toString(),
-                  "-addmods", "junit",
-                  "-XaddReads:m1=junit",
+            = run("--module-path", MODS_DIR.toString(),
+                  "--add-modules", "junit",
+                  "--add-reads", "m1=junit",
                   "-m", MAIN)
                 .getExitValue();
 
@@ -104,17 +104,17 @@
 
 
     /**
-     * Exercise -XaddReads:m1=ALL-UNNAMED by running with junit on the
+     * Exercise --add-reads m1=ALL-UNNAMED by running with junit on the
      * class path.
      */
     public void testJUnitOnClassPath() throws Exception {
 
-        // java -mp mods -cp mods/junit.jar -XaddReads:m1=ALL-UNNAMED -m ..
+        // java --module-path mods -cp mods/junit.jar --add-reads m1=ALL-UNNAMED -m ..
         String cp = MODS_DIR.resolve("junit.jar").toString();
         int exitValue
-            = run("-mp", MODS_DIR.toString(),
+            = run("--module-path", MODS_DIR.toString(),
                   "-cp", cp,
-                  "-XaddReads:m1=ALL-UNNAMED",
+                  "--add-reads", "m1=ALL-UNNAMED",
                   "-m", MAIN)
                 .getExitValue();
 
@@ -123,14 +123,14 @@
 
 
     /**
-     * Run with junit as a module on the module path but without -XaddReads.
+     * Run with junit as a module on the module path but without --add-reads.
      */
     public void testJUnitOnModulePathMissingAddReads() throws Exception {
-        // java -mp mods -addmods junit -m ..
+        // java --module-path mods --add-modules junit --module ..
         int exitValue
-            = run("-mp", MODS_DIR.toString(),
-                  "-addmods", "junit",
-                  "-m", MAIN)
+            = run("--module-path", MODS_DIR.toString(),
+                  "--add-modules", "junit",
+                  "--module", MAIN)
                 .shouldContain("IllegalAccessError")
                 .getExitValue();
 
@@ -139,13 +139,13 @@
 
 
     /**
-     * Run with junit on the class path but without -XaddReads.
+     * Run with junit on the class path but without --add-reads.
      */
     public void testJUnitOnClassPathMissingAddReads() throws Exception {
-        // java -mp mods -cp mods/junit.jar -m ..
+        // java --module-path mods -cp mods/junit.jar -m ..
         String cp = MODS_DIR.resolve("junit.jar").toString();
         int exitValue
-            = run("-mp", MODS_DIR.toString(),
+            = run("--module-path", MODS_DIR.toString(),
                   "-cp", cp,
                   "-m", MAIN)
                 .shouldContain("IllegalAccessError")
@@ -156,15 +156,15 @@
 
 
     /**
-     * Exercise -XaddReads with a more than one source module.
+     * Exercise --add-reads with a more than one source module.
      */
     public void testJUnitWithMultiValueOption() throws Exception {
 
         int exitValue
-            = run("-mp", MODS_DIR.toString(),
-                  "-addmods", "java.xml,junit",
-                  "-XaddReads:m1=java.xml,junit",
-                  "-m", MAIN)
+            = run("--module-path", MODS_DIR.toString(),
+                  "--add-modules", "java.xml,junit",
+                  "--add-reads", "m1=java.xml,junit",
+                  "--module", MAIN)
                 .getExitValue();
 
         assertTrue(exitValue == 0);
@@ -172,31 +172,31 @@
 
 
     /**
-     * Exercise -XaddReads where the target module is specified more than once
+     * Exercise --add-reads where the target module is specified more than once
      */
     public void testWithTargetSpecifiedManyTimes() throws Exception {
 
         int exitValue
-            = run("-mp", MODS_DIR.toString(),
-                "-addmods", "java.xml,junit",
-                "-XaddReads:m1=java.xml",
-                "-XaddReads:m1=junit",
-                "-m", MAIN)
-                .shouldContain("specified more than once")
-                .getExitValue();
+            = run("--module-path", MODS_DIR.toString(),
+                  "--add-modules", "java.xml,junit",
+                  "--add-reads", "m1=java.xml",
+                  "--add-reads", "m1=junit",
+                  "-m", MAIN)
+                  .shouldContain("specified more than once")
+                 .getExitValue();
 
         assertTrue(exitValue != 0);
     }
 
 
     /**
-     * Exercise -XaddReads with bad values
+     * Exercise --add-reads with bad values
      */
     @Test(dataProvider = "badvalues")
     public void testWithBadValue(String value, String ignore) throws Exception {
 
-        //  -XaddExports:$VALUE -version
-        assertTrue(run("-XaddReads:" + value, "-version").getExitValue() != 0);
+        //  --add-exports $VALUE -version
+        assertTrue(run("--add-reads", value, "-version").getExitValue() != 0);
     }
 
     @DataProvider(name = "badvalues")
--- a/jdk/test/tools/launcher/modules/basic/BasicTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/tools/launcher/modules/basic/BasicTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -37,7 +37,7 @@
 import java.nio.file.Path;
 import java.nio.file.Paths;
 
-import static jdk.testlibrary.ProcessTools.*;
+import jdk.testlibrary.ProcessTools;
 
 import org.testng.annotations.BeforeTest;
 import org.testng.annotations.Test;
@@ -72,6 +72,16 @@
         assertTrue(compiled, "test module did not compile");
     }
 
+    /**
+     * Execute "java" with the given arguments, returning the exit code.
+     */
+    private int exec(String... args) throws Exception {
+       return ProcessTools.executeTestJava(args)
+                .outputTo(System.out)
+                .errorTo(System.out)
+                .getExitValue();
+    }
+
 
     /**
      * The initial module is loaded from an exploded module
@@ -81,20 +91,28 @@
         String subdir = MODS_DIR.resolve(TEST_MODULE).toString();
         String mid = TEST_MODULE + "/" + MAIN_CLASS;
 
-        // java -mp mods -m $TESTMODULE/$MAINCLASS
-        int exitValue
-            = executeTestJava("-mp", dir, "-m", mid)
-                .outputTo(System.out)
-                .errorTo(System.out)
-                .getExitValue();
+        // java --module-path mods -module $TESTMODULE/$MAINCLASS
+        int exitValue = exec("--module-path", dir, "--module", mid);
+        assertTrue(exitValue == 0);
+
+        // java --module-path mods/$TESTMODULE --module $TESTMODULE/$MAINCLASS
+        exitValue = exec("--module-path", subdir, "--module", mid);
         assertTrue(exitValue == 0);
 
-        // java -mp mods/$TESTMODULE -m $TESTMODULE/$MAINCLASS
-        exitValue
-            = executeTestJava("-mp", subdir, "-m", mid)
-                .outputTo(System.out)
-                .errorTo(System.out)
-                .getExitValue();
+        // java --module-path=mods --module=$TESTMODULE/$MAINCLASS
+        exitValue = exec("--module-path=" + dir, "--module=" + mid);
+        assertTrue(exitValue == 0);
+
+        // java --module-path=mods/$TESTMODULE --module=$TESTMODULE/$MAINCLASS
+        exitValue = exec("--module-path=" + subdir, "--module=" + mid);
+        assertTrue(exitValue == 0);
+
+        // java -p mods -m $TESTMODULE/$MAINCLASS
+        exitValue = exec("-p", dir, "-m", mid);
+        assertTrue(exitValue == 0);
+
+        // java -p mods/$TESTMODULE -m $TESTMODULE/$MAINCLASS
+        exitValue = exec("-p", subdir, "-m", mid);
         assertTrue(exitValue == 0);
     }
 
@@ -119,22 +137,14 @@
                 .run(args);
         assertTrue(success);
 
-        // java -mp mlib -m $TESTMODULE
-        int exitValue
-            = executeTestJava("-mp", dir.toString(),
-                              "-m", TEST_MODULE)
-                .outputTo(System.out)
-                .errorTo(System.out)
-                .getExitValue();
+        // java --module-path mlib -module $TESTMODULE
+        int exitValue = exec("--module-path", dir.toString(),
+                             "--module", TEST_MODULE);
         assertTrue(exitValue == 0);
 
-        // java -mp mlib/m.jar -m $TESTMODULE
-        exitValue
-            = executeTestJava("-mp", jar.toString(),
-                              "-m", TEST_MODULE)
-                .outputTo(System.out)
-                .errorTo(System.out)
-                .getExitValue();
+        // java --module-path mlib/m.jar -module $TESTMODULE
+        exitValue = exec("--module-path", jar.toString(),
+                         "--module", TEST_MODULE);
         assertTrue(exitValue == 0);
     }
 
@@ -157,14 +167,9 @@
         jdk.tools.jmod.JmodTask task = new jdk.tools.jmod.JmodTask();
         assertEquals(task.run(args), 0);
 
-        // java -mp mods -m $TESTMODULE
-        int exitValue
-            = executeTestJava("-mp", dir.toString(),
-                "-m", TEST_MODULE)
-                .outputTo(System.out)
-                .errorTo(System.out)
-                .getExitValue();
-
+        // java --module-path mods --module $TESTMODULE
+        int exitValue = exec("--module-path", dir.toString(),
+                             "--module", TEST_MODULE);
         assertTrue(exitValue != 0);
     }
 
@@ -177,14 +182,8 @@
         String mp = "DoesNotExist" + File.pathSeparator + MODS_DIR.toString();
         String mid = TEST_MODULE + "/" + MAIN_CLASS;
 
-        // java -mp mods -m $TESTMODULE/$MAINCLASS
-        int exitValue
-            = executeTestJava("-mp", mp,
-                              "-m", mid)
-                .outputTo(System.out)
-                .errorTo(System.out)
-                .getExitValue();
-
+        // java --module-path mods --module $TESTMODULE/$MAINCLASS
+        int exitValue = exec("--module-path", mp, "--module", mid);
         assertTrue(exitValue == 0);
     }
 
@@ -195,15 +194,8 @@
     public void testTryRunWithBadModule() throws Exception {
         String modulepath = MODS_DIR.toString();
 
-        // java -mp mods -m $TESTMODULE
-        int exitValue
-            = executeTestJava("-mp", modulepath,
-                              "-m", "rhubarb")
-                .outputTo(System.out)
-                .errorTo(System.out)
-                .shouldContain("not found")
-                .getExitValue();
-
+        // java --module-path mods -m $TESTMODULE
+        int exitValue = exec("--module-path", modulepath, "-m", "rhubarb");
         assertTrue(exitValue != 0);
     }
 
@@ -216,14 +208,8 @@
         String modulepath = MODS_DIR.toString();
         String mid = TEST_MODULE + "/p.rhubarb";
 
-        // java -mp mods -m $TESTMODULE/$MAINCLASS
-        int exitValue
-            = executeTestJava("-mp", modulepath,
-                              "-m", mid)
-                .outputTo(System.out)
-                .errorTo(System.out)
-                .getExitValue();
-
+        // java --module-path mods -m $TESTMODULE/$MAINCLASS
+        int exitValue = exec("--module-path", modulepath, "-m", mid);
         assertTrue(exitValue != 0);
     }
 
@@ -248,15 +234,8 @@
                 .run(args);
         assertTrue(success);
 
-        // java -mp mods -m $TESTMODULE
-        int exitValue
-            = executeTestJava("-mp", dir.toString(),
-                              "-m", TEST_MODULE)
-                .outputTo(System.out)
-                .errorTo(System.out)
-                .shouldContain("does not have a MainClass attribute")
-                .getExitValue();
-
+        // java --module-path mods -m $TESTMODULE
+        int exitValue = exec("--module-path", dir.toString(), "-m", TEST_MODULE);
         assertTrue(exitValue != 0);
     }
 
@@ -269,14 +248,8 @@
         String modulepath = MODS_DIR.toString();
         String mid = "java.base/" + MAIN_CLASS;
 
-        // java -mp mods -m $TESTMODULE/$MAINCLASS
-        int exitValue
-            = executeTestJava("-mp", modulepath,
-                              "-m", mid)
-                .outputTo(System.out)
-                .errorTo(System.out)
-                .getExitValue();
-
+        // java --module-path mods --module $TESTMODULE/$MAINCLASS
+        int exitValue = exec("--module-path", modulepath, "--module", mid);
         assertTrue(exitValue != 0);
     }
 
--- a/jdk/test/tools/launcher/modules/dryrun/DryRunTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/tools/launcher/modules/dryrun/DryRunTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -69,11 +69,11 @@
         // javac -d mods/$TESTMODULE src/$TESTMODULE/**
         assertTrue(CompilerUtils.compile(SRC_DIR.resolve(M_MODULE),
                                          MODS_DIR,
-                                         "-modulesourcepath", SRC_DIR.toString()));
+                                         "--module-source-path", SRC_DIR.toString()));
 
         assertTrue(CompilerUtils.compile(SRC_DIR.resolve(TEST_MODULE),
                                          MODS_DIR,
-                                         "-modulesourcepath", SRC_DIR.toString()));
+                                         "--module-source-path", SRC_DIR.toString()));
 
         Files.createDirectories(LIBS_DIR);
 
@@ -101,7 +101,7 @@
         String mid = TEST_MODULE + "/" + MAIN_CLASS;
 
         // no resolution failure
-        int exitValue = exec("--dry-run", "-modulepath", dir, "-m", mid);
+        int exitValue = exec("--dry-run", "--module-path", dir, "-m", mid);
         assertTrue(exitValue == 0);
     }
 
@@ -112,23 +112,23 @@
         String dir = MODS_DIR.toString();
         String mid = TEST_MODULE + "/" + MAIN_CLINIT_CLASS;
 
-        int exitValue = exec("--dry-run", "-modulepath", dir, "-m", mid);
+        int exitValue = exec("--dry-run", "--module-path", dir, "-m", mid);
         assertTrue(exitValue == 0);
 
         // expect the test to fail if main class is initialized
-        exitValue = exec("-modulepath", dir, "-m", mid);
+        exitValue = exec("--module-path", dir, "-m", mid);
         assertTrue(exitValue != 0);
     }
 
     /**
-     * Test non-existence module in -addmods
+     * Test non-existence module in --add-modules
      */
     public void testNonExistAddModules() throws Exception {
         String dir = MODS_DIR.toString();
         String mid = TEST_MODULE + "/" + MAIN_CLASS;
 
-        int exitValue = exec("--dry-run", "-modulepath", dir,
-                             "-addmods", "non.existence",
+        int exitValue = exec("--dry-run", "--module-path", dir,
+                             "--add-modules", "non.existence",
                              "-m", mid);
         assertTrue(exitValue != 0);
     }
@@ -163,24 +163,24 @@
                         LIBS_DIR.resolve(TEST_MODULE + ".jar").toString();
         String mid = TEST_MODULE + "/" + MAIN_CLASS;
 
-        // test main method with and without -addmods mm
-        int exitValue = exec("-modulepath", LIBS_DIR.toString(),
+        // test main method with and without --add-modules mm
+        int exitValue = exec("--module-path", LIBS_DIR.toString(),
                              "-m", mid);
         assertTrue(exitValue != 0);
 
-        exitValue = exec("-modulepath", LIBS_DIR.toString(),
-                         "-addmods", M_MODULE,
+        exitValue = exec("--module-path", LIBS_DIR.toString(),
+                         "--add-modules", M_MODULE,
                          "-m", mid);
         assertTrue(exitValue == 0);
 
-        // test dry run with and without -addmods m
+        // test dry run with and without --add-modules m
         // no resolution failure
-        exitValue = exec("--dry-run", "-modulepath", LIBS_DIR.toString(),
+        exitValue = exec("--dry-run", "--module-path", LIBS_DIR.toString(),
                          "-m", mid);
         assertTrue(exitValue == 0);
 
-        exitValue = exec("--dry-run", "-modulepath", LIBS_DIR.toString(),
-                         "-addmods", M_MODULE,
+        exitValue = exec("--dry-run", "--module-path", LIBS_DIR.toString(),
+                         "--add-modules", M_MODULE,
                          "-m", mid);
         assertTrue(exitValue == 0);
     }
@@ -193,7 +193,7 @@
         String mid = TEST_MODULE + "/" + MAIN_CLASS;
 
         // resolution failure
-        int exitValue = exec("--dry-run", "-modulepath", subdir, "-m", mid);
+        int exitValue = exec("--dry-run", "--module-path", subdir, "-m", mid);
         assertTrue(exitValue != 0);
     }
 
--- a/jdk/test/tools/launcher/modules/limitmods/LimitModsTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/tools/launcher/modules/limitmods/LimitModsTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -27,7 +27,7 @@
  * @modules java.desktop java.compact1 jdk.compiler
  * @build LimitModsTest CompilerUtils jdk.testlibrary.*
  * @run testng LimitModsTest
- * @summary Basic tests for java -limitmods
+ * @summary Basic tests for java --limit-modules
  */
 
 import java.nio.file.Path;
@@ -66,13 +66,13 @@
 
 
     /**
-     * Basic test of -limitmods to limit which platform modules are observable.
+     * Basic test of --limit-modules to limit which platform modules are observable.
      */
     public void testLimitingPlatformModules() throws Exception {
         int exitValue;
 
-        // java -limitmods java.base -listmods
-        exitValue = executeTestJava("-limitmods", "java.base", "-listmods")
+        // java --limit-modules java.base --list-modules
+        exitValue = executeTestJava("--limit-modules", "java.base", "--list-modules")
             .outputTo(System.out)
             .errorTo(System.out)
             .shouldContain("java.base")
@@ -83,8 +83,8 @@
         assertTrue(exitValue == 0);
 
 
-        // java -limitmods java.compact1 -listmods
-        exitValue = executeTestJava("-limitmods", "java.compact1", "-listmods")
+        // java --limit-modules java.compact1 --list-modules
+        exitValue = executeTestJava("--limit-modules", "java.compact1", "--list-modules")
             .outputTo(System.out)
             .errorTo(System.out)
             .shouldContain("java.base")
@@ -98,15 +98,15 @@
 
 
     /**
-     * Test -limitmods with -addmods
+     * Test --limit-modules with --add-modules
      */
     public void testWithAddMods() throws Exception {
         int exitValue;
 
-        // java -limitmods java.base -addmods java.logging -listmods
-        exitValue = executeTestJava("-limitmods", "java.base",
-                                    "-addmods", "java.logging",
-                                    "-listmods")
+        // java --limit-modules java.base --add-modules java.logging --list-modules
+        exitValue = executeTestJava("--limit-modules", "java.base",
+                                    "--add-modules", "java.logging",
+                                    "--list-modules")
             .outputTo(System.out)
             .errorTo(System.out)
             .shouldContain("java.base")
@@ -117,11 +117,11 @@
         assertTrue(exitValue == 0);
 
 
-        // java -limitmods java.base -addmods java.sql -listmods
+        // java --limit-modules java.base --add-modules java.sql --list-modules
         // This should fail because java.sql has dependences beyond java.base
-        exitValue = executeTestJava("-limitmods", "java.base",
-                                    "-addmods", "java.sql",
-                                    "-listmods")
+        exitValue = executeTestJava("--limit-modules", "java.base",
+                                    "--add-modules", "java.sql",
+                                    "--list-modules")
             .outputTo(System.out)
             .errorTo(System.out)
             .getExitValue();
@@ -131,14 +131,14 @@
 
 
     /**
-     * Run class path application with -limitmods
+     * Run class path application with --limit-modules
      */
     public void testUnnamedModule() throws Exception {
         String classpath = MODS_DIR.resolve(TEST_MODULE).toString();
 
-        // java -limitmods java.base -cp mods/$TESTMODULE ...
+        // java --limit-modules java.base -cp mods/$TESTMODULE ...
         int exitValue1
-            = executeTestJava("-limitmods", "java.base",
+            = executeTestJava("--limit-modules", "java.base",
                               "-cp", classpath,
                               MAIN_CLASS)
                 .outputTo(System.out)
@@ -149,9 +149,9 @@
         assertTrue(exitValue1 != 0);
 
 
-        // java -limitmods java.base -cp mods/$TESTMODULE ...
+        // java --limit-modules java.base -cp mods/$TESTMODULE ...
         int exitValue2
-            = executeTestJava("-limitmods", "java.desktop",
+            = executeTestJava("--limit-modules", "java.desktop",
                               "-cp", classpath,
                              MAIN_CLASS)
                 .outputTo(System.out)
@@ -163,16 +163,16 @@
 
 
     /**
-     * Run named module with -limitmods
+     * Run named module with --limit-modules
      */
     public void testNamedModule() throws Exception {
 
         String modulepath = MODS_DIR.toString();
         String mid = TEST_MODULE + "/" + MAIN_CLASS;
 
-        // java -limitmods java.base -mp mods -m $TESTMODULE/$MAINCLASS
-        int exitValue = executeTestJava("-limitmods", "java.base",
-                                        "-mp", modulepath,
+        // java --limit-modules java.base --module-path mods -m $TESTMODULE/$MAINCLASS
+        int exitValue = executeTestJava("--limit-modules", "java.base",
+                                        "--module-path", modulepath,
                                         "-m", mid)
                 .outputTo(System.out)
                 .errorTo(System.out)
@@ -180,9 +180,9 @@
 
         assertTrue(exitValue != 0);
 
-        // java -limitmods java.desktop -mp mods -m $TESTMODULE/$MAINCLASS
-        exitValue = executeTestJava("-limitmods", "java.desktop",
-                                    "-mp", modulepath,
+        // java --limit-modules java.desktop --module-path mods -m $TESTMODULE/$MAINCLASS
+        exitValue = executeTestJava("--limit-modules", "java.desktop",
+                                    "--module-path", modulepath,
                                     "-m", mid)
                 .outputTo(System.out)
                 .errorTo(System.out)
--- a/jdk/test/tools/launcher/modules/listmods/ListModsTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/tools/launcher/modules/listmods/ListModsTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -27,7 +27,7 @@
  * @modules java.se
  * @build ListModsTest CompilerUtils jdk.testlibrary.*
  * @run testng ListModsTest
- * @summary Basic test for java -listmods
+ * @summary Basic test for java --list-modules
  */
 
 import java.nio.file.Path;
@@ -41,7 +41,7 @@
 import static org.testng.Assert.*;
 
 /**
- * Basic tests for java -listmods
+ * Basic tests for java --list-modules
  */
 
 public class ListModsTest {
@@ -55,13 +55,13 @@
     public void setup() throws Exception {
         boolean compiled;
 
-        // javac -d mods/m1 -mp mods src/m1/**
+        // javac -d mods/m1 --module-path mods src/m1/**
         compiled = CompilerUtils.compile(
                 SRC_DIR.resolve("m1"),
                 MODS_DIR.resolve("m1"));
         assertTrue(compiled);
 
-        // javac -d upgrademods/java.transaction -mp mods src/java.transaction/**
+        // javac -d upgrademods/java.transaction --module-path mods src/java.transaction/**
         compiled = CompilerUtils.compile(
                 SRC_DIR.resolve("java.transaction"),
                 UPGRADEMODS_DIR.resolve("java.transaction"));
@@ -73,7 +73,7 @@
     @Test
     public void testListAll() throws Exception {
         OutputAnalyzer output
-            = executeTestJava("-listmods")
+            = executeTestJava("--list-modules")
                 .outputTo(System.out)
                 .errorTo(System.out);
         output.shouldContain("java.base");
@@ -85,7 +85,7 @@
     @Test
     public void testListOneModule() throws Exception {
         OutputAnalyzer output
-            = executeTestJava("-listmods:java.base")
+            = executeTestJava("--list-modules=java.base")
                 .outputTo(System.out)
                 .errorTo(System.out);
         output.shouldContain("java.base");
@@ -97,7 +97,7 @@
     @Test
     public void testListTwoModules() throws Exception {
         OutputAnalyzer output
-            = executeTestJava("-listmods:java.base,java.xml")
+            = executeTestJava("--list-modules", "java.base,java.xml")
                 .outputTo(System.out)
                 .errorTo(System.out);
         output.shouldContain("java.base");
@@ -111,7 +111,7 @@
     @Test
     public void testListUnknownModule() throws Exception {
         OutputAnalyzer output
-            = executeTestJava("-listmods:java.rhubarb")
+            = executeTestJava("--list-modules", "java.rhubarb")
                 .outputTo(System.out)
                 .errorTo(System.out);
         output.shouldNotContain("java.base");
@@ -123,7 +123,7 @@
     @Test
     public void testListWithModulePath() throws Exception {
         OutputAnalyzer output
-            = executeTestJava("-mp", MODS_DIR.toString(), "-listmods")
+            = executeTestJava("--module-path", MODS_DIR.toString(), "--list-modules")
                 .outputTo(System.out)
                 .errorTo(System.out);
         output.shouldContain("java.base");
@@ -135,8 +135,8 @@
     @Test
     public void testListWithUpgradeModulePath() throws Exception {
         OutputAnalyzer output
-            = executeTestJava("-upgrademodulepath", UPGRADEMODS_DIR.toString(),
-                              "-listmods:java.transaction")
+            = executeTestJava("--upgrade-module-path", UPGRADEMODS_DIR.toString(),
+                              "--list-modules", "java.transaction")
                 .outputTo(System.out)
                 .errorTo(System.out);
         output.shouldContain("exports javax.transaction.atomic");
@@ -147,7 +147,7 @@
     @Test
     public void testListWithLimitMods1() throws Exception {
         OutputAnalyzer output
-            = executeTestJava("-limitmods", "java.compact1", "-listmods")
+            = executeTestJava("--limit-modules", "java.compact1", "--list-modules")
                 .outputTo(System.out)
                 .errorTo(System.out);
         output.shouldContain("java.compact1");
@@ -160,9 +160,9 @@
     @Test
     public void testListWithLimitMods2() throws Exception {
         OutputAnalyzer output
-            = executeTestJava("-mp", MODS_DIR.toString(),
-                              "-limitmods", "java.compact1",
-                              "-listmods")
+            = executeTestJava("--module-path", MODS_DIR.toString(),
+                              "--limit-modules", "java.compact1",
+                              "--list-modules")
                 .outputTo(System.out)
                 .errorTo(System.out);
         output.shouldContain("java.base");
@@ -172,12 +172,12 @@
 
 
     /**
-     * java -version -listmods => should print version and exit
+     * java -version --list-modules => should print version and exit
      */
     @Test
     public void testListWithPrintVersion1() throws Exception {
         OutputAnalyzer output
-            = executeTestJava("-version", "-listmods")
+            = executeTestJava("-version", "--list-modules")
                 .outputTo(System.out)
                 .errorTo(System.out);
         output.shouldNotContain("java.base");
@@ -187,12 +187,12 @@
 
 
     /**
-     * java -listmods -version => should list modules and exit
+     * java --list-modules -version => should list modules and exit
      */
     @Test
     public void testListWithPrintVersion2() throws Exception {
         OutputAnalyzer output
-            = executeTestJava("-listmods", "-version")
+            = executeTestJava("--list-modules", "-version")
                 .outputTo(System.out)
                 .errorTo(System.out);
         output.shouldContain("java.base");
--- a/jdk/test/tools/launcher/modules/patch/basic/PatchTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/tools/launcher/modules/patch/basic/PatchTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -27,7 +27,7 @@
  * @modules jdk.compiler
  * @build PatchTest CompilerUtils JarUtils jdk.testlibrary.*
  * @run testng PatchTest
- * @summary Basic test for -Xpatch
+ * @summary Basic test for --patch-module
  */
 
 import java.io.File;
@@ -45,13 +45,13 @@
 
 
 /**
- * Compiles and launches a test that uses -Xpatch with two directories of
- * classes to override existing and add new classes to modules in the
- * boot layer.
+ * Compiles and launches a test that uses --patch-module with two directories
+ * of classes to override existing classes and add new classes to modules in
+ * the boot layer.
  *
- * The classes overridden or added via -Xpatch all define a public no-arg
- * constructor and override toString to return "hi". This allows the launched
- * test to check that the overridden classes are loaded.
+ * The classes overridden or added via --patch-module all define a public
+ * no-arg constructor and override toString to return "hi". This allows the
+ * launched test to check that the overridden classes are loaded.
  */
 
 @Test
@@ -76,7 +76,7 @@
     private static final Path PATCHES_DIR = Paths.get("patches");
 
 
-    // the classes overridden or added with -Xpatch
+    // the classes overridden or added with --patch-module
     private static final String[] CLASSES = {
 
         // java.base = boot loader
@@ -137,15 +137,15 @@
         String arg = Stream.of(CLASSES).collect(Collectors.joining(","));
 
         int exitValue
-            =  executeTestJava("-Xpatch:java.base=" + basePatches,
-                               "-Xpatch:jdk.naming.dns=" + dnsPatches,
-                               "-Xpatch:jdk.compiler=" + compilerPatches,
-                               "-XaddExports:java.base/java.lang2=test",
-                               "-XaddExports:jdk.naming.dns/com.sun.jndi.dns=test",
-                               "-XaddExports:jdk.naming.dns/com.sun.jndi.dns2=test",
-                               "-XaddExports:jdk.compiler/com.sun.tools.javac2=test",
-                               "-addmods", "jdk.naming.dns,jdk.compiler",
-                               "-mp", MODS_DIR.toString(),
+            =  executeTestJava("--patch-module", "java.base=" + basePatches,
+                               "--patch-module", "jdk.naming.dns=" + dnsPatches,
+                               "--patch-module", "jdk.compiler=" + compilerPatches,
+                               "--add-exports", "java.base/java.lang2=test",
+                               "--add-exports", "jdk.naming.dns/com.sun.jndi.dns=test",
+                               "--add-exports", "jdk.naming.dns/com.sun.jndi.dns2=test",
+                               "--add-exports", "jdk.compiler/com.sun.tools.javac2=test",
+                               "--add-modules", "jdk.naming.dns,jdk.compiler",
+                               "--module-path", MODS_DIR.toString(),
                                "-m", "test/jdk.test.Main", arg)
                 .outputTo(System.out)
                 .errorTo(System.out)
@@ -156,7 +156,7 @@
 
 
     /**
-     * Run test with -Xpatch and exploded patches
+     * Run test with ---patch-module and exploded patches
      */
     public void testWithExplodedPatches() throws Exception {
 
@@ -175,7 +175,7 @@
 
 
     /**
-     * Run test with -Xpatch and patches in JAR files
+     * Run test with ---patch-module and patches in JAR files
      */
     public void testWithJarPatches() throws Exception {
 
@@ -195,7 +195,7 @@
 
 
     /**
-     * Run test with -Xpatch and patches in JAR files and exploded patches
+     * Run test with ---patch-module and patches in JAR files and exploded patches
      */
     public void testWithJarAndExplodedPatches() throws Exception {
 
--- a/jdk/test/tools/launcher/modules/patch/basic/src/test/jdk/test/Main.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/tools/launcher/modules/patch/basic/src/test/jdk/test/Main.java	Wed Jul 05 22:05:22 2017 +0200
@@ -22,7 +22,7 @@
  */
 
 /**
- * Used with -Xpatch to exercise the replacement or addition of classes
+ * Used with --patch-module to exercise the replacement or addition of classes
  * in modules that are linked into the runtime image.
  */
 
--- a/jdk/test/tools/launcher/modules/patch/systemmodules/PatchSystemModules.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/tools/launcher/modules/patch/systemmodules/PatchSystemModules.java	Wed Jul 05 22:05:22 2017 +0200
@@ -69,7 +69,7 @@
         for (String name : modules) {
             assertTrue(CompilerUtils.compile(src.resolve(name),
                                              MODS_DIR,
-                                             "-modulesourcepath", src.toString()));
+                                             "--module-source-path", src.toString()));
         }
 
         // compile patched source
@@ -93,16 +93,16 @@
 
         Path home = Paths.get(JAVA_HOME);
         runTest(home,
-                "-mp", MODS_DIR.toString(),
+                "--module-path", MODS_DIR.toString(),
                 "-m", "m1/p1.Main", "1");
         runTest(home,
-                "-Xpatch:java.base=" + patchedJavaBase.toString(),
-                "-mp", MODS_DIR.toString(),
+                "--patch-module", "java.base=" + patchedJavaBase,
+                "--module-path", MODS_DIR.toString(),
                 "-m", "m1/p1.Main", "1");
 
         runTest(home,
-                "-Xpatch:m2=" + patchedM2.toString(),
-                "-mp", MODS_DIR.toString(),
+                "--patch-module", "m2=" + patchedM2.toString(),
+                "--module-path", MODS_DIR.toString(),
                 "-m", "m1/p1.Main", "2");
     }
 
@@ -117,10 +117,10 @@
         runTest(IMAGE,
                 "-m", "m1/p1.Main", "1");
         runTest(IMAGE,
-                "-Xpatch:java.base=" + patchedJavaBase.toString(),
+                "--patch-module", "java.base=" + patchedJavaBase,
                 "-m", "m1/p1.Main", "1");
         runTest(IMAGE,
-                "-Xpatch:m2=" + patchedM2.toString(),
+                "--patch-module", "m2=" + patchedM2.toString(),
                 "-m", "m1/p1.Main", "2");
     }
 
@@ -138,12 +138,12 @@
 
         // Fail to upgrade m1.jar with mismatched hash
         runTestWithExitCode(getJava(IMAGE),
-                "-upgrademodulepath", m1.toString(),
+                "--upgrade-module-path", m1.toString(),
                 "-m", "m1/p1.Main");
 
         runTestWithExitCode(getJava(IMAGE),
-                "-Xpatch:java.base=" + PATCH_DIR.resolve(JAVA_BASE).toString(),
-                "-upgrademodulepath", m1.toString(),
+                "--patch-module", "java.base=" + PATCH_DIR.resolve(JAVA_BASE),
+                "--upgrade-module-path", m1.toString(),
                 "-m", "m1/p1.Main", "1");
     }
 
@@ -185,14 +185,14 @@
 
         jar("--create",
             "--file=" + m2.toString(),
-            "--modulepath", JARS_DIR.toString(),
+            "--module-path", JARS_DIR.toString(),
             "--hash-modules", "m1",
             "-C", MODS_DIR.resolve("m2").toString(), ".");
 
 
         String mpath = JARS_DIR.toString() + File.pathSeparator + JMODS.toString();
-        execTool("jlink", "--modulepath", mpath,
-                 "--addmods", "m1",
+        execTool("jlink", "--module-path", mpath,
+                 "--add-modules", "m1",
                  "--output", IMAGE.toString());
     }
 
@@ -216,7 +216,7 @@
     }
 
     static String getJava(Path image) {
-        boolean isWindows = System.getProperty("os.name").toLowerCase().startsWith("win");
+        boolean isWindows = System.getProperty("os.name").startsWith("Windows");
         Path java = image.resolve("bin").resolve(isWindows ? "java.exe" : "java");
         if (Files.notExists(java))
             throw new RuntimeException(java + " not found");
--- a/jdk/test/tools/launcher/modules/patch/systemmodules/src1/java.base/jdk/internal/modules/SystemModules.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/tools/launcher/modules/patch/systemmodules/src1/java.base/jdk/internal/modules/SystemModules.java	Wed Jul 05 22:05:22 2017 +0200
@@ -24,7 +24,7 @@
 package jdk.internal.module;
 
 /*
- * Test -Xpatch:java.base=jdk/modules/java.base to override
+ * Test --patch-module java.base=jdk/modules/java.base to override
  * java.base with an exploded image
  */
 public final class SystemModules {
--- a/jdk/test/tools/launcher/modules/upgrademodulepath/UpgradeModulePathTest.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/tools/launcher/modules/upgrademodulepath/UpgradeModulePathTest.java	Wed Jul 05 22:05:22 2017 +0200
@@ -27,7 +27,7 @@
  * @modules jdk.compiler
  * @build UpgradeModulePathTest CompilerUtils jdk.testlibrary.*
  * @run testng UpgradeModulePathTest
- * @summary Basic test for java -upgrademodulepath
+ * @summary Basic test for java --upgrade-module-path
  */
 
 import java.io.File;
@@ -65,19 +65,19 @@
                 MODS_DIR.resolve("java.enterprise"));
         assertTrue(compiled);
 
-        // javac -d upgrademods/java.transaction -mp mods src/java.transaction/**
+        // javac -d upgrademods/java.transaction --module-path mods src/java.transaction/**
         compiled = CompilerUtils.compile(
                 SRC_DIR.resolve("java.transaction"),
                 UPGRADEDMODS_DIR.resolve("java.transaction"),
-                "-mp", MODS_DIR.toString());
+                "--module-path", MODS_DIR.toString());
         assertTrue(compiled);
 
-        // javac -d mods -upgrademodulepath upgrademods -mp mods src/test/**
+        // javac -d mods --upgrade-module-path upgrademods --module-path mods src/test/**
         compiled = CompilerUtils.compile(
                 SRC_DIR.resolve("test"),
                 MODS_DIR.resolve("test"),
-                "-upgrademodulepath", UPGRADEDMODS_DIR.toString(),
-                "-mp", MODS_DIR.toString());
+                "--upgrade-module-path", UPGRADEDMODS_DIR.toString(),
+                "--module-path", MODS_DIR.toString());
         assertTrue(compiled);
 
     }
@@ -92,8 +92,8 @@
 
         int exitValue
             = executeTestJava(
-                "-upgrademodulepath", UPGRADEDMODS_DIR.toString(),
-                "-mp", MODS_DIR.toString(),
+                "--upgrade-module-path", UPGRADEDMODS_DIR.toString(),
+                "--module-path", MODS_DIR.toString(),
                 "-m", mid)
             .outputTo(System.out)
             .errorTo(System.out)
@@ -116,8 +116,8 @@
 
         int exitValue
             = executeTestJava(
-                "-upgrademodulepath", upgrademodulepath,
-                "-mp", MODS_DIR.toString(),
+                "--upgrade-module-path", upgrademodulepath,
+                "--module-path", MODS_DIR.toString(),
                 "-m", mid)
             .outputTo(System.out)
             .errorTo(System.out)
--- a/jdk/test/tools/lib/tests/Helper.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/tools/lib/tests/Helper.java	Wed Jul 05 22:05:22 2017 +0200
@@ -164,7 +164,7 @@
         Path srcMod = src.resolve(moduleName);
         JImageGenerator.generateModuleInfo(srcMod, packages, dependencies);
         Path destination = classes.resolve(moduleName);
-        if (!JImageGenerator.compile(srcMod, destination, "-modulepath", modulePath, "-g")) {
+        if (!JImageGenerator.compile(srcMod, destination, "--module-path", modulePath, "-g")) {
             throw new AssertionError("Compilation failure");
         }
         return destination;
--- a/jdk/test/tools/lib/tests/JImageGenerator.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/tools/lib/tests/JImageGenerator.java	Wed Jul 05 22:05:22 2017 +0200
@@ -106,10 +106,10 @@
     private static final String POST_PROCESS_OPTION = "--post-process-path";
     private static final String MAIN_CLASS_OPTION = "--main-class";
     private static final String CLASS_PATH_OPTION = "--class-path";
-    private static final String MODULE_PATH_OPTION = "--modulepath";
-    private static final String ADD_MODS_OPTION = "--addmods";
-    private static final String LIMIT_MODS_OPTION = "--limitmods";
-    private static final String PLUGINS_MODULE_PATH = "--plugin-module-path";
+    private static final String MODULE_PATH_OPTION = "--module-path";
+    private static final String ADD_MODULES_OPTION = "--add-modules";
+    private static final String LIMIT_MODULES_OPTION = "--limit-modules";
+    private static final String PLUGIN_MODULE_PATH = "--plugin-module-path";
 
     private static final String CMDS_OPTION = "--cmds";
     private static final String CONFIG_OPTION = "--config";
@@ -534,7 +534,7 @@
                 options.add(dir.toString());
             }
             if (!pluginModulePath.isEmpty()) {
-                options.add(PLUGINS_MODULE_PATH);
+                options.add(PLUGIN_MODULE_PATH);
                 options.add(toPath(pluginModulePath));
             }
             options.addAll(this.options);
@@ -632,11 +632,11 @@
                 options.add(output.toString());
             }
             if (!addMods.isEmpty()) {
-                options.add(ADD_MODS_OPTION);
+                options.add(ADD_MODULES_OPTION);
                 options.add(addMods.stream().collect(Collectors.joining(",")));
             }
             if (!limitMods.isEmpty()) {
-                options.add(LIMIT_MODS_OPTION);
+                options.add(LIMIT_MODULES_OPTION);
                 options.add(limitMods.stream().collect(Collectors.joining(",")));
             }
             if (!jars.isEmpty() || !jmods.isEmpty()) {
@@ -648,7 +648,7 @@
                 options.add(modulePath);
             }
             if (!pluginModulePath.isEmpty()) {
-                options.add(PLUGINS_MODULE_PATH);
+                options.add(PLUGIN_MODULE_PATH);
                 options.add(toPath(pluginModulePath));
             }
             options.addAll(this.options);
--- a/jdk/test/tools/pack200/Utils.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/tools/pack200/Utils.java	Wed Jul 05 22:05:22 2017 +0200
@@ -111,7 +111,7 @@
 
         compiler("-d",
                 XCLASSES.getName(),
-                "-XaddExports:jdk.jdeps/com.sun.tools.classfile=ALL-UNNAMED",
+                "--add-exports=jdk.jdeps/com.sun.tools.classfile=ALL-UNNAMED",
                 "@" + tmpFile.getAbsolutePath());
 
         jar("cvfe",
@@ -148,7 +148,7 @@
         init();
         List<String> cmds = new ArrayList<String>();
         cmds.add(getJavaCmd());
-        cmds.add("-XaddExports:jdk.jdeps/com.sun.tools.classfile=ALL-UNNAMED");
+        cmds.add("--add-exports=jdk.jdeps/com.sun.tools.classfile=ALL-UNNAMED");
         cmds.add("-cp");
         cmds.add(VerifierJar.getName());
         cmds.add("sun.tools.pack.verify.Main");
--- a/jdk/test/tools/pack200/pack200-verifier/make/build.xml	Mon Aug 15 08:28:26 2016 +0200
+++ b/jdk/test/tools/pack200/pack200-verifier/make/build.xml	Wed Jul 05 22:05:22 2017 +0200
@@ -27,7 +27,7 @@
 	   destdir="${build}/classes"
 	   verbose="no"
 	   debug="on">
-       <compilerarg value="-XaddExports:jdk.jdeps/com.sun.tools.classfile"/>
+       <compilerarg value="--add-exports=jdk.jdeps/com.sun.tools.classfile"/>
      </javac>
   </target>
 
--- a/make/CompileJavaModules.gmk	Mon Aug 15 08:28:26 2016 +0200
+++ b/make/CompileJavaModules.gmk	Wed Jul 05 22:05:22 2017 +0200
@@ -502,8 +502,8 @@
     HEADERS := $(SUPPORT_OUTPUTDIR)/headers, \
     ADD_JAVAC_FLAGS := \
         $($(MODULE)_ADD_JAVAC_FLAGS) \
-        -modulesourcepath $(MODULESOURCEPATH) \
-        -modulepath $(MODULEPATH) \
+        --module-source-path $(MODULESOURCEPATH) \
+        --module-path $(MODULEPATH) \
         -system none, \
 ))
 
--- a/make/CreateJmods.gmk	Mon Aug 15 08:28:26 2016 +0200
+++ b/make/CreateJmods.gmk	Wed Jul 05 22:05:22 2017 +0200
@@ -77,7 +77,7 @@
 
     EXCLUDE_PATTERN := $(strip $(subst $(SPACE),|,$(strip $(ALL_UPGRADEABLE_MODULES))))
 
-    JMOD_FLAGS += --modulepath $(JMODS_DIR) \
+    JMOD_FLAGS += --module-path $(JMODS_DIR) \
         --hash-modules '^(?!$(EXCLUDE_PATTERN))'
   endif
 endif
@@ -102,7 +102,7 @@
             --os-name $(REQUIRED_OS_NAME) \
             --os-arch $(OPENJDK_TARGET_CPU_LEGACY) \
             --os-version $(REQUIRED_OS_VERSION) \
-            --modulepath $(JMODS_DIR) \
+            --module-path $(JMODS_DIR) \
             --exclude '**{_the.*,*.diz,*.debuginfo,*.dSYM/**,*.pdb,*.map}' \
 	    $(JMOD_FLAGS) $(SUPPORT_OUTPUTDIR)/jmods/$(notdir $@)
 	$(MV) $(SUPPORT_OUTPUTDIR)/jmods/$(notdir $@) $@
--- a/make/Images.gmk	Mon Aug 15 08:28:26 2016 +0200
+++ b/make/Images.gmk	Wed Jul 05 22:05:22 2017 +0200
@@ -127,7 +127,7 @@
     /jdk.localedata/** \
     #
 
-JLINK_TOOL := $(JLINK) --modulepath $(IMAGES_OUTPUTDIR)/jmods \
+JLINK_TOOL := $(JLINK) --module-path $(IMAGES_OUTPUTDIR)/jmods \
     --endian $(OPENJDK_BUILD_CPU_ENDIAN) \
     --release-info $(BASE_RELEASE_FILE) \
     --order-resources=$(call CommaList, $(JLINK_ORDER_RESOURCES)) \
@@ -142,7 +142,7 @@
 	$(ECHO) Creating jdk jimage
 	$(RM) -r $(JDK_IMAGE_DIR)
 	$(JLINK_TOOL) --output $(JDK_IMAGE_DIR) \
-	    --addmods $(JDK_MODULES_LIST) $(JLINK_EXTRA_OPTS)
+	    --add-modules $(JDK_MODULES_LIST) $(JLINK_EXTRA_OPTS)
 	$(TOUCH) $@
 
 $(JRE_IMAGE_DIR)/$(JIMAGE_TARGET_FILE): $(JMODS) \
@@ -150,7 +150,7 @@
 	$(ECHO) Creating jre jimage
 	$(RM) -r $(JRE_IMAGE_DIR)
 	$(JLINK_TOOL) --output $(JRE_IMAGE_DIR) \
-	    --addmods $(JRE_MODULES_LIST)
+	    --add-modules $(JRE_MODULES_LIST)
 	$(TOUCH) $@
 
 JRE_COMPACT1_IMAGE_DIR := $(JRE_IMAGE_DIR)-compact1
@@ -161,7 +161,7 @@
     $(call DependOnVariable, JRE_COMPACT1_MODULES_LIST) $(BASE_RELEASE_FILE)
 	$(ECHO) Creating jre compact1 jimage
 	$(RM) -r $(JRE_COMPACT1_IMAGE_DIR)
-	$(JLINK_TOOL) --addmods $(JRE_COMPACT1_MODULES_LIST) \
+	$(JLINK_TOOL) --add-modules $(JRE_COMPACT1_MODULES_LIST) \
 	    --output $(JRE_COMPACT1_IMAGE_DIR)
 	$(TOUCH) $@
 
@@ -169,7 +169,7 @@
     $(call DependOnVariable, JRE_COMPACT2_MODULES_LIST) $(BASE_RELEASE_FILE)
 	$(ECHO) Creating jre compact2 jimage
 	$(RM) -r $(JRE_COMPACT2_IMAGE_DIR)
-	$(JLINK_TOOL) --addmods $(JRE_COMPACT2_MODULES_LIST) \
+	$(JLINK_TOOL) --add-modules $(JRE_COMPACT2_MODULES_LIST) \
 	    --output $(JRE_COMPACT2_IMAGE_DIR)
 	$(TOUCH) $@
 
@@ -177,7 +177,7 @@
     $(call DependOnVariable, JRE_COMPACT3_MODULES_LIST) $(BASE_RELEASE_FILE)
 	$(ECHO) Creating jre compact3 jimage
 	$(RM) -r $(JRE_COMPACT3_IMAGE_DIR)
-	$(JLINK_TOOL) --addmods $(JRE_COMPACT3_MODULES_LIST) \
+	$(JLINK_TOOL) --add-modules $(JRE_COMPACT3_MODULES_LIST) \
 	    --output $(JRE_COMPACT3_IMAGE_DIR)
 	$(TOUCH) $@
 
--- a/make/InterimImage.gmk	Mon Aug 15 08:28:26 2016 +0200
+++ b/make/InterimImage.gmk	Wed Jul 05 22:05:22 2017 +0200
@@ -39,7 +39,7 @@
 JMODS := $(patsubst %, $(IMAGES_OUTPUTDIR)/jmods/%.jmod, $(INTERIM_IMAGE_MODULES))
 
 JLINK_TOOL := $(JLINK) \
-    --modulepath $(IMAGES_OUTPUTDIR)/jmods \
+    --module-path $(IMAGES_OUTPUTDIR)/jmods \
     --endian $(OPENJDK_BUILD_CPU_ENDIAN)
 
 $(INTERIM_IMAGE_DIR)/$(JIMAGE_TARGET_FILE): $(JMODS) \
@@ -48,7 +48,7 @@
 	$(RM) -r $(INTERIM_IMAGE_DIR)
 	$(JLINK_TOOL) \
 	    --output $(INTERIM_IMAGE_DIR) \
-	    --addmods $(INTERIM_MODULES_LIST)
+	    --add-modules $(INTERIM_MODULES_LIST)
 	$(TOUCH) $@
 
 TARGETS += $(INTERIM_IMAGE_DIR)/$(JIMAGE_TARGET_FILE)
--- a/make/Javadoc.gmk	Mon Aug 15 08:28:26 2016 +0200
+++ b/make/Javadoc.gmk	Wed Jul 05 22:05:22 2017 +0200
@@ -425,9 +425,9 @@
           $(call COMMON_JAVADOCTAGS) ; \
           $(call OptionOnly,-Xdoclint:reference) ; \
           $(call OptionOnly,-Xdoclint/package:-org.omg.*$(COMMA)jdk.internal.logging.*) ; \
-          $(call OptionPair,-system,none) ; \
-	  $(call OptionPair,-modulesourcepath,$(RELEASEDOCS_MODULESOURCEPATH)) ; \
-	  $(call OptionPair,-addmods,$(COREAPI_MODULES)) ; \
+          $(call OptionPair,--system,none) ; \
+	  $(call OptionPair,--module-source-path,$(RELEASEDOCS_MODULESOURCEPATH)) ; \
+	  $(call OptionPair,--add-modules,$(COREAPI_MODULES)) ; \
 	  $(call OptionPair,-encoding,ISO-8859-1) ; \
 	  $(call OptionOnly,-splitIndex) ; \
 	  $(call OptionPair,-overview,$(COREAPI_OVERVIEW)) ; \
@@ -488,9 +488,9 @@
 	@($(call COMMON_JAVADOCFLAGS) ; \
           $(call COMMON_JAVADOCTAGS) ; \
 	  $(call OptionOnly,-Xdoclint:all) ; \
-          $(call OptionPair,-system,none) ; \
-	  $(call OptionPair,-modulesourcepath,$(RELEASEDOCS_MODULESOURCEPATH)) ; \
-	  $(call OptionPair,-addmods,$(DOCLETAPI_MODULES)) ; \
+          $(call OptionPair,--system,none) ; \
+	  $(call OptionPair,--module-source-path,$(RELEASEDOCS_MODULESOURCEPATH)) ; \
+	  $(call OptionPair,--add-modules,$(DOCLETAPI_MODULES)) ; \
 	  $(call OptionPair,-encoding,ascii) ; \
 	  $(call OptionOnly,-breakiterator) ; \
 	  $(call OptionPair,-doctitle,$(DOCLETAPI_DOCTITLE)) ; \
@@ -550,9 +550,9 @@
 	@($(call COMMON_JAVADOCFLAGS) ; \
           $(call COMMON_JAVADOCTAGS) ; \
 	  $(call OptionOnly,-Xdoclint:all) ; \
-          $(call OptionPair,-system,none) ; \
-	  $(call OptionPair,-modulesourcepath,$(RELEASEDOCS_MODULESOURCEPATH)) ; \
-	  $(call OptionPair,-addmods,$(OLD_DOCLETAPI_MODULES)) ; \
+          $(call OptionPair,--system,none) ; \
+	  $(call OptionPair,--module-source-path,$(RELEASEDOCS_MODULESOURCEPATH)) ; \
+	  $(call OptionPair,--add-modules,$(OLD_DOCLETAPI_MODULES)) ; \
 	  $(call OptionPair,-encoding,ascii) ; \
 	  $(call OptionOnly,-breakiterator) ; \
 	  $(call OptionPair,-doctitle,$(OLD_DOCLETAPI_DOCTITLE)) ; \
@@ -605,9 +605,9 @@
 	@($(call COMMON_JAVADOCFLAGS) ; \
           $(call COMMON_JAVADOCTAGS) ; \
 	  $(call OptionOnly,-Xdoclint:all) ; \
-          $(call OptionPair,-system,none) ; \
-	  $(call OptionPair,-modulesourcepath,$(RELEASEDOCS_MODULESOURCEPATH)) ; \
-	  $(call OptionPair,-addmods,$(TAGLETAPI_MODULES)) ; \
+          $(call OptionPair,--system,none) ; \
+	  $(call OptionPair,--module-source-path,$(RELEASEDOCS_MODULESOURCEPATH)) ; \
+	  $(call OptionPair,--add-modules,$(TAGLETAPI_MODULES)) ; \
 	  $(call OptionPair,-encoding,ascii) ; \
 	  $(call OptionOnly,-breakiterator) ; \
 	  $(call OptionPair,-doctitle,$(TAGLETAPI_DOCTITLE)) ; \
@@ -667,9 +667,9 @@
 	@($(call COMMON_JAVADOCFLAGS) ; \
           $(call COMMON_JAVADOCTAGS) ; \
 	  $(call OptionOnly,-Xdoclint:none) ; \
-          $(call OptionPair,-system,none) ; \
-	  $(call OptionPair,-modulesourcepath,$(RELEASEDOCS_MODULESOURCEPATH)) ; \
-	  $(call OptionPair,-addmods,$(DOMAPI_MODULES)) ; \
+          $(call OptionPair,--system,none) ; \
+	  $(call OptionPair,--module-source-path,$(RELEASEDOCS_MODULESOURCEPATH)) ; \
+	  $(call OptionPair,--add-modules,$(DOMAPI_MODULES)) ; \
 	  $(call OptionPair,-encoding,ascii) ; \
 	  $(call OptionOnly,-splitIndex) ; \
 	  $(call OptionPair,-doctitle,$(DOMAPI_DOCTITLE)) ; \
@@ -736,9 +736,9 @@
 	@($(call COMMON_JAVADOCFLAGS) ; \
           $(call COMMON_JAVADOCTAGS) ; \
 	  $(call OptionOnly,-Xdoclint:none) ; \
-          $(call OptionPair,-system,none) ; \
-	  $(call OptionPair,-modulesourcepath,$(RELEASEDOCS_MODULESOURCEPATH)) ; \
-	  $(call OptionPair,-addmods,$(JDI_MODULES)) ; \
+          $(call OptionPair,--system,none) ; \
+	  $(call OptionPair,--module-source-path,$(RELEASEDOCS_MODULESOURCEPATH)) ; \
+	  $(call OptionPair,--add-modules,$(JDI_MODULES)) ; \
 	  $(call OptionPair,-encoding,ascii) ; \
 	  $(call OptionPair,-overview,$(JDI_OVERVIEW)) ; \
 	  $(call OptionPair,-doctitle,$(JDI_DOCTITLE)) ; \
@@ -829,9 +829,9 @@
 	@($(call COMMON_JAVADOCFLAGS) ; \
           $(call COMMON_JAVADOCTAGS) ; \
 	  $(call OptionOnly,-Xdoclint:none) ; \
-          $(call OptionPair,-system,none) ; \
-	  $(call OptionPair,-modulesourcepath,$(RELEASEDOCS_MODULESOURCEPATH)) ; \
-	  $(call OptionPair,-addmods,$(JAAS_MODULES)) ; \
+          $(call OptionPair,--system,none) ; \
+	  $(call OptionPair,--module-source-path,$(RELEASEDOCS_MODULESOURCEPATH)) ; \
+	  $(call OptionPair,--add-modules,$(JAAS_MODULES)) ; \
 	  $(call OptionPair,-encoding,ascii) ; \
 	  $(call OptionPair,-overview,$(JAAS_OVERVIEW)) ; \
 	  $(call OptionPair,-doctitle,$(JAAS_DOCTITLE)) ; \
@@ -888,9 +888,9 @@
 	@($(call COMMON_JAVADOCFLAGS) ; \
           $(call COMMON_JAVADOCTAGS) ; \
 	  $(call OptionOnly,-Xdoclint:none) ; \
-          $(call OptionPair,-system,none) ; \
-	  $(call OptionPair,-modulesourcepath,$(RELEASEDOCS_MODULESOURCEPATH)) ; \
-	  $(call OptionPair,-addmods,$(JGSS_MODULES)) ; \
+          $(call OptionPair,--system,none) ; \
+	  $(call OptionPair,--module-source-path,$(RELEASEDOCS_MODULESOURCEPATH)) ; \
+	  $(call OptionPair,--add-modules,$(JGSS_MODULES)) ; \
 	  $(call OptionPair,-encoding,ascii) ; \
 	  $(call OptionOnly,-nodeprecatedlist) ; \
 	  $(call OptionPair,-overview,$(JGSS_OVERVIEW)) ; \
@@ -947,9 +947,9 @@
 	@($(call COMMON_JAVADOCFLAGS) ; \
           $(call COMMON_JAVADOCTAGS) ; \
 	  $(call OptionOnly,-Xdoclint:none) ; \
-          $(call OptionPair,-system,none) ; \
-	  $(call OptionPair,-modulesourcepath,$(RELEASEDOCS_MODULESOURCEPATH)) ; \
-	  $(call OptionPair,-addmods,$(SMARTCARDIO_MODULES)) ; \
+          $(call OptionPair,--system,none) ; \
+	  $(call OptionPair,--module-source-path,$(RELEASEDOCS_MODULESOURCEPATH)) ; \
+	  $(call OptionPair,--add-modules,$(SMARTCARDIO_MODULES)) ; \
 	  $(call OptionPair,-encoding,ascii) ; \
 	  $(call OptionOnly,-nodeprecatedlist) ; \
 	  $(call OptionPair,-doctitle,$(SMARTCARDIO_DOCTITLE)) ; \
@@ -1004,9 +1004,9 @@
 	@($(call COMMON_JAVADOCFLAGS) ; \
           $(call COMMON_JAVADOCTAGS) ; \
 	  $(call OptionOnly,-Xdoclint:none) ; \
-          $(call OptionPair,-system,none) ; \
-	  $(call OptionPair,-modulesourcepath,$(RELEASEDOCS_MODULESOURCEPATH)) ; \
-	  $(call OptionPair,-addmods,$(HTTPSERVER_MODULES)) ; \
+          $(call OptionPair,--system,none) ; \
+	  $(call OptionPair,--module-source-path,$(RELEASEDOCS_MODULESOURCEPATH)) ; \
+	  $(call OptionPair,--add-modules,$(HTTPSERVER_MODULES)) ; \
 	  $(call OptionPair,-encoding,ascii) ; \
 	  $(call OptionOnly,-nodeprecatedlist) ; \
 	  $(call OptionPair,-doctitle,$(HTTPSERVER_DOCTITLE)) ; \
@@ -1061,9 +1061,9 @@
 	@($(call COMMON_JAVADOCFLAGS) ; \
           $(call COMMON_JAVADOCTAGS) ; \
 	  $(call OptionOnly,-Xdoclint:none) ; \
-          $(call OptionPair,-system,none) ; \
-	  $(call OptionPair,-modulesourcepath,$(RELEASEDOCS_MODULESOURCEPATH)) ; \
-	  $(call OptionPair,-addmods,$(JSOBJECT_MODULES)) ; \
+          $(call OptionPair,--system,none) ; \
+	  $(call OptionPair,--module-source-path,$(RELEASEDOCS_MODULESOURCEPATH)) ; \
+	  $(call OptionPair,--add-modules,$(JSOBJECT_MODULES)) ; \
 	  $(call OptionPair,-encoding,ascii) ; \
 	  $(call OptionOnly,-nodeprecatedlist) ; \
 	  $(call OptionPair,-doctitle,$(JSOBJECT_DOCTITLE)) ; \
@@ -1121,9 +1121,9 @@
 	@($(call COMMON_JAVADOCFLAGS) ; \
           $(call COMMON_JAVADOCTAGS) ; \
 	  $(call OptionOnly,-Xdoclint:none) ; \
-          $(call OptionPair,-system,none) ; \
-	  $(call OptionPair,-modulesourcepath,$(RELEASEDOCS_MODULESOURCEPATH)) ; \
-	  $(call OptionPair,-addmods,$(MGMT_MODULES)) ; \
+          $(call OptionPair,--system,none) ; \
+	  $(call OptionPair,--module-source-path,$(RELEASEDOCS_MODULESOURCEPATH)) ; \
+	  $(call OptionPair,--add-modules,$(MGMT_MODULES)) ; \
 	  $(call OptionPair,-encoding,ascii) ; \
 	  $(call OptionOnly,-nodeprecatedlist) ; \
 	  $(call OptionPair,-overview,$(MGMT_OVERVIEW)) ; \
@@ -1179,9 +1179,9 @@
 	@($(call COMMON_JAVADOCFLAGS) ; \
           $(call COMMON_JAVADOCTAGS) ; \
 	  $(call OptionOnly,-Xdoclint:none) ; \
-          $(call OptionPair,-system,none) ; \
-	  $(call OptionPair,-modulesourcepath,$(RELEASEDOCS_MODULESOURCEPATH)) ; \
-	  $(call OptionPair,-addmods,$(ATTACH_MODULES)) ; \
+          $(call OptionPair,--system,none) ; \
+	  $(call OptionPair,--module-source-path,$(RELEASEDOCS_MODULESOURCEPATH)) ; \
+	  $(call OptionPair,--add-modules,$(ATTACH_MODULES)) ; \
 	  $(call OptionPair,-encoding,ascii) ; \
 	  $(call OptionOnly,-nodeprecatedlist) ; \
 	  $(call OptionPair,-doctitle,$(ATTACH_DOCTITLE)) ; \
@@ -1236,9 +1236,9 @@
 	@($(call COMMON_JAVADOCFLAGS) ; \
           $(call COMMON_JAVADOCTAGS) ; \
 	  $(call OptionOnly,-Xdoclint:none) ; \
-          $(call OptionPair,-system,none) ; \
-	  $(call OptionPair,-modulesourcepath,$(RELEASEDOCS_MODULESOURCEPATH)) ; \
-	  $(call OptionPair,-addmods,$(JCONSOLE_MODULES)) ; \
+          $(call OptionPair,--system,none) ; \
+	  $(call OptionPair,--module-source-path,$(RELEASEDOCS_MODULESOURCEPATH)) ; \
+	  $(call OptionPair,--add-modules,$(JCONSOLE_MODULES)) ; \
 	  $(call OptionPair,-encoding,ascii) ; \
 	  $(call OptionOnly,-nodeprecatedlist) ; \
 	  $(call OptionPair,-doctitle,$(JCONSOLE_DOCTITLE)) ; \
@@ -1294,9 +1294,9 @@
 	@($(call COMMON_JAVADOCFLAGS) ; \
           $(call COMMON_JAVADOCTAGS) ; \
 	  $(call OptionOnly,-Xdoclint:all) ; \
-          $(call OptionPair,-system,none) ; \
-	  $(call OptionPair,-modulesourcepath,$(RELEASEDOCS_MODULESOURCEPATH)) ; \
-	  $(call OptionPair,-addmods,$(JSHELLAPI_MODULES)) ; \
+          $(call OptionPair,--system,none) ; \
+	  $(call OptionPair,--module-source-path,$(RELEASEDOCS_MODULESOURCEPATH)) ; \
+	  $(call OptionPair,--add-modules,$(JSHELLAPI_MODULES)) ; \
 	  $(call OptionPair,-encoding,ascii) ; \
 	  $(call OptionPair,-overview,$(JSHELLAPI_OVERVIEW)) ; \
 	  $(call OptionPair,-doctitle,$(JSHELLAPI_DOCTITLE)) ; \
@@ -1353,9 +1353,9 @@
 	@($(call COMMON_JAVADOCFLAGS) ; \
           $(call COMMON_JAVADOCTAGS) ; \
 	  $(call OptionOnly,-Xdoclint:all) ; \
-          $(call OptionPair,-system,none) ; \
-	  $(call OptionPair,-modulesourcepath,$(RELEASEDOCS_MODULESOURCEPATH)) ; \
-	  $(call OptionPair,-addmods,$(TREEAPI_MODULES)) ; \
+          $(call OptionPair,--system,none) ; \
+	  $(call OptionPair,--module-source-path,$(RELEASEDOCS_MODULESOURCEPATH)) ; \
+	  $(call OptionPair,--add-modules,$(TREEAPI_MODULES)) ; \
 	  $(call OptionPair,-encoding,ascii) ; \
 	  $(call OptionPair,-doctitle,$(TREEAPI_DOCTITLE)) ; \
 	  $(call OptionPair,-windowtitle,$(TREEAPI_WINDOWTITLE) $(DRAFT_WINTITLE)); \
@@ -1412,9 +1412,9 @@
 	@($(call COMMON_JAVADOCFLAGS) ; \
           $(call COMMON_JAVADOCTAGS) ; \
 	  $(call OptionOnly,-Xdoclint:all) ; \
-          $(call OptionPair,-system,none) ; \
-	  $(call OptionPair,-modulesourcepath,$(RELEASEDOCS_MODULESOURCEPATH)) ; \
-	  $(call OptionPair,-addmods,$(NASHORNAPI_MODULES)) ; \
+          $(call OptionPair,--system,none) ; \
+	  $(call OptionPair,--module-source-path,$(RELEASEDOCS_MODULESOURCEPATH)) ; \
+	  $(call OptionPair,--add-modules,$(NASHORNAPI_MODULES)) ; \
 	  $(call OptionPair,-encoding,ascii) ; \
 	  $(call OptionPair,-doctitle,$(NASHORNAPI_DOCTITLE)) ; \
 	  $(call OptionPair,-windowtitle,$(NASHORNAPI_WINDOWTITLE) $(DRAFT_WINTITLE)); \
@@ -1471,9 +1471,9 @@
 	@($(call COMMON_JAVADOCFLAGS) ; \
           $(call COMMON_JAVADOCTAGS) ; \
 	  $(call OptionOnly,-Xdoclint:all) ; \
-          $(call OptionPair,-system,none) ; \
-	  $(call OptionPair,-modulesourcepath,$(RELEASEDOCS_MODULESOURCEPATH)) ; \
-	  $(call OptionPair,-addmods,$(DYNALINKAPI_MODULES)) ; \
+          $(call OptionPair,--system,none) ; \
+	  $(call OptionPair,--module-source-path,$(RELEASEDOCS_MODULESOURCEPATH)) ; \
+	  $(call OptionPair,--add-modules,$(DYNALINKAPI_MODULES)) ; \
 	  $(call OptionPair,-encoding,ascii) ; \
 	  $(call OptionPair,-doctitle,$(DYNALINKAPI_DOCTITLE)) ; \
 	  $(call OptionPair,-windowtitle,$(DYNALINKAPI_WINDOWTITLE) $(DRAFT_WINTITLE)); \
@@ -1527,9 +1527,9 @@
 	@($(call COMMON_JAVADOCFLAGS) ; \
           $(call COMMON_JAVADOCTAGS) ; \
 	  $(call OptionOnly,-Xdoclint:none) ; \
-          $(call OptionPair,-system,none) ; \
-	  $(call OptionPair,-modulesourcepath,$(RELEASEDOCS_MODULESOURCEPATH)) ; \
-	  $(call OptionPair,-addmods,$(SCTPAPI_MODULES)) ; \
+          $(call OptionPair,--system,none) ; \
+	  $(call OptionPair,--module-source-path,$(RELEASEDOCS_MODULESOURCEPATH)) ; \
+	  $(call OptionPair,--add-modules,$(SCTPAPI_MODULES)) ; \
 	  $(call OptionPair,-encoding,ascii) ; \
 	  $(call OptionOnly,-nodeprecatedlist) ; \
 	  $(call OptionPair,-doctitle,$(SCTPAPI_DOCTITLE)) ; \
@@ -1584,9 +1584,9 @@
 	@($(call COMMON_JAVADOCFLAGS) ; \
 	  $(call COMMON_JAVADOCTAGS) ; \
 	  $(call OptionOnly,-Xdoclint:all) ; \
-          $(call OptionPair,-system,none) ; \
-	  $(call OptionPair,-modulesourcepath,$(RELEASEDOCS_MODULESOURCEPATH)) ; \
-	  $(call OptionPair,-addmods,$(JACCESSAPI_MODULES)) ; \
+          $(call OptionPair,--system,none) ; \
+	  $(call OptionPair,--module-source-path,$(RELEASEDOCS_MODULESOURCEPATH)) ; \
+	  $(call OptionPair,--add-modules,$(JACCESSAPI_MODULES)) ; \
 	  $(call OptionPair,-encoding,ascii) ; \
 	  $(call OptionOnly,-nodeprecatedlist) ; \
 	  $(call OptionPair,-doctitle,$(JACCESSAPI_DOCTITLE)) ; \
@@ -1641,9 +1641,9 @@
 	@($(call COMMON_JAVADOCFLAGS) ; \
           $(call COMMON_JAVADOCTAGS) ; \
 	  $(call OptionOnly,-Xdoclint:none) ; \
-          $(call OptionPair,-system,none) ; \
-	  $(call OptionPair,-modulesourcepath,$(RELEASEDOCS_MODULESOURCEPATH)) ; \
-	  $(call OptionPair,-addmods,$(JDKNET_MODULES)) ; \
+          $(call OptionPair,--system,none) ; \
+	  $(call OptionPair,--module-source-path,$(RELEASEDOCS_MODULESOURCEPATH)) ; \
+	  $(call OptionPair,--add-modules,$(JDKNET_MODULES)) ; \
 	  $(call OptionPair,-encoding,ascii) ; \
 	  $(call OptionOnly,-nodeprecatedlist) ; \
 	  $(call OptionPair,-doctitle,$(JDKNET_DOCTITLE)) ; \
@@ -1702,9 +1702,9 @@
 	@($(call COMMON_JAVADOCFLAGS) ; \
           $(call COMMON_JAVADOCTAGS) ; \
 	  $(call OptionOnly,-Xdoclint:none) ; \
-          $(call OptionPair,-system,none) ; \
-	  $(call OptionPair,-modulesourcepath,$(RELEASEDOCS_MODULESOURCEPATH)) ; \
-	  $(call OptionPair,-addmods,$(JLINK_PLUGIN_MODULES)) ; \
+          $(call OptionPair,--system,none) ; \
+	  $(call OptionPair,--module-source-path,$(RELEASEDOCS_MODULESOURCEPATH)) ; \
+	  $(call OptionPair,--add-modules,$(JLINK_PLUGIN_MODULES)) ; \
 	  $(call OptionPair,-encoding,ascii) ; \
 	  $(call OptionOnly,-nodeprecatedlist) ; \
 	  $(call OptionPair,-doctitle,$(JLINK_PLUGIN_DOCTITLE)) ; \
--- a/make/common/MakeBase.gmk	Mon Aug 15 08:28:26 2016 +0200
+++ b/make/common/MakeBase.gmk	Wed Jul 05 22:05:22 2017 +0200
@@ -828,7 +828,7 @@
 endif
 
 ################################################################################
-# Return a string suitable for use after a -classpath or -modulepath option. It
+# Return a string suitable for use after a -classpath or --module-path option. It
 # will be correct and safe to use on all platforms. Arguments are given as space
 # separate classpath entries. Safe for multiple nested calls.
 # param 1 : A space separated list of classpath entries
--- a/make/common/SetupJavaCompilers.gmk	Mon Aug 15 08:28:26 2016 +0200
+++ b/make/common/SetupJavaCompilers.gmk	Wed Jul 05 22:05:22 2017 +0200
@@ -88,7 +88,7 @@
 $(eval $(call SetupJavaCompiler,GENERATE_USINGJDKBYTECODE, \
     JVM := $(JAVA_SMALL), \
     JAVAC := $(NEW_JAVAC), \
-    FLAGS := -upgrademodulepath $(JDK_OUTPUTDIR)/modules -system none $(DISABLE_WARNINGS), \
+    FLAGS := --upgrade-module-path $(JDK_OUTPUTDIR)/modules -system none $(DISABLE_WARNINGS), \
     SERVER_DIR := $(SJAVAC_SERVER_DIR), \
     SERVER_JVM := $(SJAVAC_SERVER_JAVA)))
 
--- a/nashorn/.hgtags	Mon Aug 15 08:28:26 2016 +0200
+++ b/nashorn/.hgtags	Wed Jul 05 22:05:22 2017 +0200
@@ -364,3 +364,4 @@
 5a189c5b396c353786343b590f6c19a5d929f01d jdk-9+128
 68020a486500422e2c8b94b0f35cafe54c9e219a jdk-9+129
 0de67a63e2c73781ecf5979a2f3aa9619a445c37 jdk-9+130
+ee77c6b3713ab293e027ac3ea1cc16f86dac535f jdk-9+131
--- a/nashorn/buildtools/nasgen/project.properties	Mon Aug 15 08:28:26 2016 +0200
+++ b/nashorn/buildtools/nasgen/project.properties	Wed Jul 05 22:05:22 2017 +0200
@@ -40,8 +40,8 @@
 javac.debug=true
 
 nasgen.module.imports=\
-    -XaddExports:java.base/jdk.internal.org.objectweb.asm=ALL-UNNAMED \
-    -XaddExports:java.base/jdk.internal.org.objectweb.asm.util=ALL-UNNAMED
+    --add-exports java.base/jdk.internal.org.objectweb.asm=ALL-UNNAMED \
+    --add-exports java.base/jdk.internal.org.objectweb.asm.util=ALL-UNNAMED
 
 meta.inf.dir=${src.dir}/META-INF
 run.classpath=\
--- a/nashorn/make/BuildNashorn.gmk	Mon Aug 15 08:28:26 2016 +0200
+++ b/nashorn/make/BuildNashorn.gmk	Wed Jul 05 22:05:22 2017 +0200
@@ -44,8 +44,8 @@
 $(eval $(call SetupJavaCompiler,GENERATE_NEWBYTECODE_DEBUG, \
     JVM := $(JAVA), \
     JAVAC := $(NEW_JAVAC), \
-    FLAGS := -g -source 9 -target 9 -upgrademodulepath "$(JDK_OUTPUTDIR)/modules/" \
-         -system none -modulesourcepath "$(MODULESOURCEPATH)", \
+    FLAGS := -g -source 9 -target 9 --upgrade-module-path "$(JDK_OUTPUTDIR)/modules/" \
+         --system none --module-source-path "$(MODULESOURCEPATH)", \
     SERVER_DIR := $(SJAVAC_SERVER_DIR), \
     SERVER_JVM := $(SJAVAC_SERVER_JAVA)))
 
@@ -76,9 +76,9 @@
 ifeq ($(BOOT_JDK_MODULAR), true)
   NASGEN_OPTIONS := \
       -cp $(BUILDTOOLS_OUTPUTDIR)/nasgen_classes \
-      -Xpatch:java.base=$(BUILDTOOLS_OUTPUTDIR)/nasgen_classes \
-      -XaddExports:java.base/jdk.internal.org.objectweb.asm=ALL-UNNAMED \
-      -XaddExports:java.base/jdk.internal.org.objectweb.asm.util=ALL-UNNAMED \
+      --patch-module java.base=$(BUILDTOOLS_OUTPUTDIR)/nasgen_classes \
+      --add-exports java.base/jdk.internal.org.objectweb.asm=ALL-UNNAMED \
+      --add-exports java.base/jdk.internal.org.objectweb.asm.util=ALL-UNNAMED \
       #
 else
   NASGEN_OPTIONS := \
--- a/nashorn/make/build.xml	Mon Aug 15 08:28:26 2016 +0200
+++ b/nashorn/make/build.xml	Wed Jul 05 22:05:22 2017 +0200
@@ -178,7 +178,7 @@
       <compilerarg value="-Xdiags:verbose"/>
       <compilerarg value="-parameters"/>
     </javac>
-    <!-- -Xpatch does not like module-info.class files! -->
+    <!-- patch-module does not like module-info.class files! -->
     <delete>
       <fileset dir="${build.classes.dir}" includes="**/module-info.class"/>
     </delete>
@@ -195,7 +195,7 @@
       <compilerarg value="-parameters"/>
       <compilerarg line="${nashorn.override.option}"/>
     </javac>
-    <!-- -Xpatch does not like module-info.class files! -->
+    <!-- patch-module does not like module-info.class files! -->
     <delete>
       <fileset dir="${build.classes.dir}" includes="**/module-info.class"/>
     </delete>
@@ -212,7 +212,7 @@
       <compilerarg value="-parameters"/>
       <compilerarg line="${nashorn.override.option}"/>
     </javac>
-    <!-- -Xpatch does not like module-info.class files! -->
+    <!-- patch-module does not like module-info.class files! -->
     <delete>
       <fileset dir="${build.classes.dir}" includes="**/module-info.class"/>
     </delete>
@@ -266,7 +266,7 @@
     <javadoc destdir="${dist.javadoc.dir}" use="yes" overview="${nashorn.module.src.dir}/overview.html"
         windowtitle="${nashorn.product.name} ${nashorn.version}"
         additionalparam="-quiet" failonerror="true" useexternalfile="true">
-      <arg value="-modulesourcepath"/>
+      <arg value="--module-source-path"/>
       <arg value="${basedir}/src/*/share/classes"/>
       <arg value="${javadoc.option}"/>
       <classpath>
@@ -285,7 +285,7 @@
     <javadoc destdir="${dist.nashornapi.javadoc.dir}" use="yes" overview="${nashorn.module.src.dir}/overview.html"
         extdirs="${nashorn.ext.path}" windowtitle="${nashorn.product.name} ${nashorn.version}"
         additionalparam="-quiet" failonerror="true" useexternalfile="true">
-      <arg value="-modulesourcepath"/>
+      <arg value="--module-source-path"/>
       <arg value="${basedir}/src/*/share/classes"/>
       <arg value="${javadoc.option}"/>
       <classpath>
@@ -302,7 +302,7 @@
     <javadoc destdir="${dist.dynalinkapi.javadoc.dir}" use="yes"
         windowtitle="Dynalink"
         additionalparam="-quiet" failonerror="true" useexternalfile="true">
-      <arg value="-modulesourcepath"/>
+      <arg value="--module-source-path"/>
       <arg value="${basedir}/src/*/share/classes"/>
       <arg value="${javadoc.option}"/>
       <classpath>
--- a/nashorn/make/project.properties	Mon Aug 15 08:28:26 2016 +0200
+++ b/nashorn/make/project.properties	Wed Jul 05 22:05:22 2017 +0200
@@ -51,9 +51,9 @@
 build.gzip=${build.dir}/nashorn.tar.gz
 
 nashorn.override.option=\
- -Xpatch:jdk.scripting.nashorn=${build.classes.dir}/jdk.scripting.nashorn \
- -Xpatch:jdk.scripting.nashorn.shell=${build.classes.dir}/jdk.scripting.nashorn.shell \
- -Xpatch:jdk.dynalink=${build.classes.dir}/jdk.dynalink
+ --patch-module jdk.scripting.nashorn=${build.classes.dir}/jdk.scripting.nashorn \
+ --patch-module jdk.scripting.nashorn.shell=${build.classes.dir}/jdk.scripting.nashorn.shell \
+ --patch-module jdk.dynalink=${build.classes.dir}/jdk.dynalink
 
 # project directory of <nashorn> ant task
 nashorntask.dir=buildtools/nashorntask
@@ -65,8 +65,8 @@
 nasgen.tool=jdk.nashorn.internal.tools.nasgen.Main
 
 nasgen.module.imports=\
-    -XaddExports:java.base/jdk.internal.org.objectweb.asm=ALL-UNNAMED \
-    -XaddExports:java.base/jdk.internal.org.objectweb.asm.util=ALL-UNNAMED
+    --add-exports java.base/jdk.internal.org.objectweb.asm=ALL-UNNAMED \
+    --add-exports java.base/jdk.internal.org.objectweb.asm.util=ALL-UNNAMED
 
 # parallel test runner tool
 parallel.test.runner=jdk.nashorn.internal.test.framework.ParallelTestRunner
@@ -142,19 +142,19 @@
     ${file.reference.snakeyaml.jar}
 
 test.module.imports=\
-    -XaddExports:jdk.scripting.nashorn/jdk.nashorn.internal.ir=ALL-UNNAMED \
-    -XaddExports:jdk.scripting.nashorn/jdk.nashorn.internal.codegen=ALL-UNNAMED \
-    -XaddExports:jdk.scripting.nashorn/jdk.nashorn.internal.parser=ALL-UNNAMED \
-    -XaddExports:jdk.scripting.nashorn/jdk.nashorn.internal.objects=ALL-UNNAMED \
-    -XaddExports:jdk.scripting.nashorn/jdk.nashorn.internal.runtime=ALL-UNNAMED \
-    -XaddExports:jdk.scripting.nashorn/jdk.nashorn.internal.runtime.doubleconv=ALL-UNNAMED \
-    -XaddExports:jdk.scripting.nashorn/jdk.nashorn.internal.runtime.linker=ALL-UNNAMED \
-    -XaddExports:jdk.scripting.nashorn/jdk.nashorn.internal.runtime.events=ALL-UNNAMED \
-    -XaddExports:jdk.scripting.nashorn/jdk.nashorn.internal.runtime.options=ALL-UNNAMED \
-    -XaddExports:jdk.scripting.nashorn/jdk.nashorn.internal.runtime.regexp=ALL-UNNAMED \
-    -XaddExports:jdk.scripting.nashorn/jdk.nashorn.internal.runtime.regexp.joni=ALL-UNNAMED \
-    -XaddExports:jdk.scripting.nashorn/jdk.nashorn.tools=ALL-UNNAMED \
-    -XaddExports:java.base/jdk.internal.org.objectweb.asm=ALL-UNNAMED
+    --add-exports jdk.scripting.nashorn/jdk.nashorn.internal.ir=ALL-UNNAMED \
+    --add-exports jdk.scripting.nashorn/jdk.nashorn.internal.codegen=ALL-UNNAMED \
+    --add-exports jdk.scripting.nashorn/jdk.nashorn.internal.parser=ALL-UNNAMED \
+    --add-exports jdk.scripting.nashorn/jdk.nashorn.internal.objects=ALL-UNNAMED \
+    --add-exports jdk.scripting.nashorn/jdk.nashorn.internal.runtime=ALL-UNNAMED \
+    --add-exports jdk.scripting.nashorn/jdk.nashorn.internal.runtime.doubleconv=ALL-UNNAMED \
+    --add-exports jdk.scripting.nashorn/jdk.nashorn.internal.runtime.linker=ALL-UNNAMED \
+    --add-exports jdk.scripting.nashorn/jdk.nashorn.internal.runtime.events=ALL-UNNAMED \
+    --add-exports jdk.scripting.nashorn/jdk.nashorn.internal.runtime.options=ALL-UNNAMED \
+    --add-exports jdk.scripting.nashorn/jdk.nashorn.internal.runtime.regexp=ALL-UNNAMED \
+    --add-exports jdk.scripting.nashorn/jdk.nashorn.internal.runtime.regexp.joni=ALL-UNNAMED \
+    --add-exports jdk.scripting.nashorn/jdk.nashorn.tools=ALL-UNNAMED \
+    --add-exports java.base/jdk.internal.org.objectweb.asm=ALL-UNNAMED
 
 meta.inf.dir=${nashorn.module.src.dir}/META-INF
 
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/OptimisticTypesPersistence.java	Mon Aug 15 08:28:26 2016 +0200
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/OptimisticTypesPersistence.java	Wed Jul 05 22:05:22 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2010, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -324,6 +324,8 @@
                 }
                 versionDir.mkdirs();
                 if (versionDir.isDirectory()) {
+                    //FIXME:Logger is disabled as Context.getContext() always returns null here because global scope object will not be created
+                    //by the time this method gets invoked
                     getLogger().info("Optimistic type persistence directory is " + versionDir);
                     return versionDir;
                 }
@@ -450,10 +452,12 @@
     private static DebugLogger getLogger() {
         try {
             return Context.getContext().getLogger(RecompilableScriptFunctionData.class);
+        } catch (final NullPointerException e) {
+            //Don't print stacktrace until we revisit this, NPE is a known issue here
         } catch (final Exception e) {
             e.printStackTrace();
-            return DebugLogger.DISABLED_LOGGER;
         }
+        return DebugLogger.DISABLED_LOGGER;
     }
 
     private static void scheduleCleanup() {
--- a/nashorn/test/TEST.ROOT	Mon Aug 15 08:28:26 2016 +0200
+++ b/nashorn/test/TEST.ROOT	Wed Jul 05 22:05:22 2017 +0200
@@ -8,7 +8,7 @@
 groups=TEST.groups
 
 # Minimum jtreg version
-requiredVersion=4.2 b02
+requiredVersion=4.2 b03
 
-# Use new form of -Xpatch
-useNewXpatch=true
+# Use new module options
+useNewOptions=true
--- a/nashorn/test/script/currently-failing/JDK-8055034.js	Mon Aug 15 08:28:26 2016 +0200
+++ b/nashorn/test/script/currently-failing/JDK-8055034.js	Wed Jul 05 22:05:22 2017 +0200
@@ -51,7 +51,7 @@
     jjsCmd = javahome + "/bin/jjs";
     jjsCmd = jjsCmd.toString().replace(/\//g, File.separator);
 }
-jjsCmd += " -J-Xpatch:" + nashornJar;
+jjsCmd += " -J--patch-module=jdk.scripting.nashorn=" + nashornJar;
 
 $ENV.PWD=System.getProperty("user.dir") // to avoid RE on Cygwin
 $EXEC(jjsCmd, "var x = Object.create(null);\nx;\nprint('PASSED');\nexit(0)");