changeset 40728:1ed235a29653

Merge
author prr
date Mon, 29 Aug 2016 08:53:32 -0700
parents e9f4bcc8dfd3 fb5226b8ac7f
children aae3aa5fd024
files jdk/make/data/cryptopolicy/limited/default_local.policy jdk/make/data/cryptopolicy/limited/exempt_local.policy jdk/make/data/cryptopolicy/unlimited/default_US_export.policy jdk/make/data/cryptopolicy/unlimited/default_local.policy jdk/make/gendata/GendataPolicyJars.gmk langtools/make/intellij/runConfigurations/jtreg__debug_.xml langtools/make/intellij/runConfigurations/jtreg__run_.xml langtools/make/intellij/utils/jtreg-live-templates.xml langtools/test/jdk/javadoc/tool/sourceOnly/p/NonSource.class langtools/test/tools/javac/defaultMethods/static/StaticInvoke.java langtools/test/tools/javac/defaultMethods/static/StaticInvoke6.out langtools/test/tools/javac/defaultMethods/static/StaticInvoke7.out langtools/test/tools/javac/generics/diamond/neg/Neg09.java langtools/test/tools/javac/generics/diamond/neg/Neg09.out
diffstat 405 files changed, 11175 insertions(+), 3705 deletions(-) [+]
line wrap: on
line diff
--- a/.hgtags	Wed Jul 20 15:07:48 2016 +0200
+++ b/.hgtags	Mon Aug 29 08:53:32 2016 -0700
@@ -374,3 +374,4 @@
 e8373543a3f0f60589b7d72b1f9b172721124caf jdk-9+129
 e613affb88d178dc7c589f1679db113d589bddb4 jdk-9+130
 4d2a15091124488080d65848b704e25599b2aaeb jdk-9+131
+2e83d21d78cd9c1d52e6cd2599e9c8aa36ea1f52 jdk-9+132
--- a/.hgtags-top-repo	Wed Jul 20 15:07:48 2016 +0200
+++ b/.hgtags-top-repo	Mon Aug 29 08:53:32 2016 -0700
@@ -374,3 +374,4 @@
 f5902d3841b82cac6e7716a20c24e8e916fb14a8 jdk-9+129
 d94d54a3192fea79234c3ac55cd0b4052d45e954 jdk-9+130
 8728756c2f70a79a90188f4019cfd6b9a275765c jdk-9+131
+a24702d4d5ab0015a5c553ed57f66fce7d85155e jdk-9+132
--- a/common/autoconf/spec.gmk.in	Wed Jul 20 15:07:48 2016 +0200
+++ b/common/autoconf/spec.gmk.in	Mon Aug 29 08:53:32 2016 -0700
@@ -251,8 +251,6 @@
 # Legacy support
 USE_NEW_HOTSPOT_BUILD:=@USE_NEW_HOTSPOT_BUILD@
 
-MACOSX_UNIVERSAL=@MACOSX_UNIVERSAL@
-
 # JDK_OUTPUTDIR specifies where a working jvm is built.
 # You can run $(JDK_OUTPUTDIR)/bin/java
 # Though the layout of the contents of $(JDK_OUTPUTDIR) is not
--- a/corba/.hgtags	Wed Jul 20 15:07:48 2016 +0200
+++ b/corba/.hgtags	Mon Aug 29 08:53:32 2016 -0700
@@ -374,3 +374,4 @@
 c3e83ccab3bb1733ae903d681879a33f85ed465c jdk-9+129
 77f9692d5976ae155773dd3e07533616bb95bae1 jdk-9+130
 f7e1d5337c2e550fe553df7a3886bbed80292ecd jdk-9+131
+1ab4b9399c4cba584f66c1c088188f2f565fbf9c jdk-9+132
--- a/corba/src/java.corba/share/classes/module-info.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/corba/src/java.corba/share/classes/module-info.java	Mon Aug 29 08:53:32 2016 -0700
@@ -23,6 +23,9 @@
  * questions.
  */
 
+/**
+ * Defines the Java binding of the OMG CORBA APIs, and the RMI-IIOP API.
+ */
 module java.corba {
     requires public java.desktop;
     requires public java.rmi;
--- a/hotspot/.hgtags	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/.hgtags	Mon Aug 29 08:53:32 2016 -0700
@@ -534,3 +534,4 @@
 e96b34b76d863ed1fa04e0eeb3f297ac17b490fd jdk-9+129
 7d54c7056328b6a2bf4877458b8f4d8cd870f93b jdk-9+130
 943bf73b49c33c2d7cbd796f6a4ae3c7a00ae932 jdk-9+131
+713951c08aa26813375175c2ab6cc99ff2a56903 jdk-9+132
--- a/hotspot/make/Dist.gmk	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/make/Dist.gmk	Mon Aug 29 08:53:32 2016 -0700
@@ -46,15 +46,6 @@
 endif
 
 ################################################################################
-# Functions to setup copying of files for variants
-
-# Support macro for SetupDistLibFile
-define macosx_universalize
-	$(MKDIR) -p $(@D)
-	$(LIPO) -create -output $@ $<
-endef
-
-################################################################################
 # Setup make rules to copy a native library and associated data.
 #
 # Parameter 1 is the name of the rule. This name is used as variable prefix,
@@ -74,16 +65,9 @@
   $1_LIB_NAME := $(LIBRARY_PREFIX)$$($1_NAME)
   $1_TARGET_DIR := $$(DIST_OUTPUTDIR)/$$(LIB_SUBDIR)/$$($1_VARIANT_TARGET_DIR)
 
-  ifeq ($(OPENJDK_TARGET_OS), macosx)
-    # We must use the 'universalize' macro to run lipo on shared libraries, at
-    # least until JDK-8069540 is fixed.
-    $1_MACRO := macosx_universalize
-  endif
-
   # Copy the the native library.
   $$(eval $$(call SetupCopyFiles, $1_COPY_LIB, \
       DEST := $$($1_TARGET_DIR), \
-      MACRO := $$($1_MACRO), \
       FILES := $$(wildcard \
           $$($1_SRC_DIR)/$$($1_LIB_NAME)$(SHARED_LIBRARY_SUFFIX)), \
   ))
--- a/hotspot/make/test/JtregNative.gmk	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/make/test/JtregNative.gmk	Mon Aug 29 08:53:32 2016 -0700
@@ -50,7 +50,6 @@
     $(HOTSPOT_TOPDIR)/test/runtime/BoolReturn \
     $(HOTSPOT_TOPDIR)/test/compiler/floatingpoint/ \
     $(HOTSPOT_TOPDIR)/test/compiler/calls \
-    $(HOTSPOT_TOPDIR)/test/compiler/native \
     $(HOTSPOT_TOPDIR)/test/serviceability/jvmti/GetNamedModule \
     $(HOTSPOT_TOPDIR)/test/testlibrary/jvmti \
     $(HOTSPOT_TOPDIR)/test/compiler/jvmci/jdk.vm.ci.code.test \
--- a/hotspot/src/cpu/aarch64/vm/frame_aarch64.cpp	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/src/cpu/aarch64/vm/frame_aarch64.cpp	Mon Aug 29 08:53:32 2016 -0700
@@ -110,17 +110,7 @@
     // Entry frame checks
     if (is_entry_frame()) {
       // an entry frame must have a valid fp.
-
-      if (!fp_safe) return false;
-
-      // Validate the JavaCallWrapper an entry frame must have
-
-      address jcw = (address)entry_frame_call_wrapper();
-
-      bool jcw_safe = (jcw < thread->stack_base()) && ( jcw > fp);
-
-      return jcw_safe;
-
+      return fp_safe && is_entry_frame_valid(thread);
     }
 
     intptr_t* sender_sp = NULL;
@@ -210,15 +200,8 @@
       }
 
       // construct the potential sender
-
       frame sender(sender_sp, sender_unextended_sp, saved_fp, sender_pc);
-
-      // Validate the JavaCallWrapper an entry frame must have
-      address jcw = (address)sender.entry_frame_call_wrapper();
-
-      bool jcw_safe = (jcw < thread->stack_base()) && ( jcw > (address)sender.fp());
-
-      return jcw_safe;
+      return sender.is_entry_frame_valid(thread);
     }
 
     CompiledMethod* nm = sender_blob->as_compiled_method_or_null();
--- a/hotspot/src/cpu/sparc/vm/frame_sparc.cpp	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/src/cpu/sparc/vm/frame_sparc.cpp	Mon Aug 29 08:53:32 2016 -0700
@@ -225,19 +225,7 @@
     // Entry frame checks
     if (is_entry_frame()) {
       // an entry frame must have a valid fp.
-
-      if (!fp_safe) {
-        return false;
-      }
-
-      // Validate the JavaCallWrapper an entry frame must have
-
-      address jcw = (address)entry_frame_call_wrapper();
-
-      bool jcw_safe = (jcw <= thread->stack_base()) && ( jcw > _FP);
-
-      return jcw_safe;
-
+      return fp_safe && is_entry_frame_valid(thread);
     }
 
     intptr_t* younger_sp = sp();
@@ -290,14 +278,8 @@
       return false;
     }
 
-    if( sender.is_entry_frame()) {
-      // Validate the JavaCallWrapper an entry frame must have
-
-      address jcw = (address)sender.entry_frame_call_wrapper();
-
-      bool jcw_safe = (jcw <= thread->stack_base()) && ( jcw > sender_fp);
-
-      return jcw_safe;
+    if (sender.is_entry_frame()) {
+      return sender.is_entry_frame_valid(thread);
     }
 
     // If the frame size is 0 something (or less) is bad because every nmethod has a non-zero frame size
@@ -357,12 +339,6 @@
     _cb = CodeCache::find_blob(_pc);
   }
   _deopt_state = unknown;
-#ifdef ASSERT
-  if ( _cb != NULL && _cb->is_compiled()) {
-    // Without a valid unextended_sp() we can't convert the pc to "original"
-    assert(!((CompiledMethod*)_cb)->is_deopt_pc(_pc), "invariant broken");
-  }
-#endif // ASSERT
 }
 
 frame::frame(intptr_t* sp, unpatchable_t, address pc, CodeBlob* cb) {
@@ -534,6 +510,7 @@
 
 
 void frame::patch_pc(Thread* thread, address pc) {
+  vmassert(_deopt_state != unknown, "frame is unpatchable");
   if(thread == Thread::current()) {
    StubRoutines::Sparc::flush_callers_register_windows_func()();
   }
--- a/hotspot/src/cpu/x86/vm/frame_x86.cpp	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/src/cpu/x86/vm/frame_x86.cpp	Mon Aug 29 08:53:32 2016 -0700
@@ -108,17 +108,7 @@
     // Entry frame checks
     if (is_entry_frame()) {
       // an entry frame must have a valid fp.
-
-      if (!fp_safe) return false;
-
-      // Validate the JavaCallWrapper an entry frame must have
-
-      address jcw = (address)entry_frame_call_wrapper();
-
-      bool jcw_safe = (jcw < thread->stack_base()) && ( jcw > fp);
-
-      return jcw_safe;
-
+      return fp_safe && is_entry_frame_valid(thread);
     }
 
     intptr_t* sender_sp = NULL;
@@ -209,15 +199,8 @@
       }
 
       // construct the potential sender
-
       frame sender(sender_sp, sender_unextended_sp, saved_fp, sender_pc);
-
-      // Validate the JavaCallWrapper an entry frame must have
-      address jcw = (address)sender.entry_frame_call_wrapper();
-
-      bool jcw_safe = (jcw < thread->stack_base()) && ( jcw > (address)sender.fp());
-
-      return jcw_safe;
+      return sender.is_entry_frame_valid(thread);
     }
 
     CompiledMethod* nm = sender_blob->as_compiled_method_or_null();
--- a/hotspot/src/cpu/x86/vm/interp_masm_x86.cpp	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/src/cpu/x86/vm/interp_masm_x86.cpp	Mon Aug 29 08:53:32 2016 -0700
@@ -1071,6 +1071,9 @@
 
     NOT_LP64(get_thread(rthread);)
 
+    cmpl(Address(rthread, JavaThread::stack_guard_state_offset()), JavaThread::stack_guard_enabled);
+    jcc(Assembler::equal, no_reserved_zone_enabling);
+
     cmpptr(rbx, Address(rthread, JavaThread::reserved_stack_activation_offset()));
     jcc(Assembler::lessEqual, no_reserved_zone_enabling);
 
--- a/hotspot/src/jdk.hotspot.agent/share/classes/sun/jvm/hotspot/SALauncher.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/src/jdk.hotspot.agent/share/classes/sun/jvm/hotspot/SALauncher.java	Mon Aug 29 08:53:32 2016 -0700
@@ -255,7 +255,8 @@
         }
 
         buildAttachArgs(newArgs, pid, exe, core, false);
-        JStack.main(newArgs.toArray(new String[newArgs.size()]));
+        JStack jstack = new JStack(false, false);
+        jstack.runWithArgs(newArgs.toArray(new String[newArgs.size()]));
     }
 
     private static void runJMAP(String[] oldArgs) {
--- a/hotspot/src/jdk.hotspot.agent/share/classes/sun/jvm/hotspot/oops/BreakpointInfo.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/src/jdk.hotspot.agent/share/classes/sun/jvm/hotspot/oops/BreakpointInfo.java	Mon Aug 29 08:53:32 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2016 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
--- a/hotspot/src/jdk.hotspot.agent/share/classes/sun/jvm/hotspot/oops/MethodCounters.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/src/jdk.hotspot.agent/share/classes/sun/jvm/hotspot/oops/MethodCounters.java	Mon Aug 29 08:53:32 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, 2016 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
--- a/hotspot/src/jdk.hotspot.agent/share/classes/sun/jvm/hotspot/runtime/ppc64/PPC64Frame.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/src/jdk.hotspot.agent/share/classes/sun/jvm/hotspot/runtime/ppc64/PPC64Frame.java	Mon Aug 29 08:53:32 2016 -0700
@@ -46,7 +46,6 @@
   private static final int SENDER_SP_OFFSET           =  0;
 
   // Interpreter frames
-  private static final int INTERPRETER_FRAME_MIRROR_OFFSET = -3; // for native calls only
   private static final int INTERPRETER_FRAME_SENDER_SP_OFFSET = -4;
   private static final int INTERPRETER_FRAME_LAST_SP_OFFSET = INTERPRETER_FRAME_SENDER_SP_OFFSET - 1;
   private static final int INTERPRETER_FRAME_MDX_OFFSET = INTERPRETER_FRAME_LAST_SP_OFFSET -1;
@@ -55,7 +54,8 @@
   private static final int INTERPRETER_FRAME_CACHE_OFFSET =INTERPRETER_FRAME_BCX_OFFSET - 1;
   private static final int INTERPRETER_FRAME_MONITORS_OFFSET = INTERPRETER_FRAME_CACHE_OFFSET - 1;
   private static final int INTERPRETER_FRAME_LOCALS_OFFSET = INTERPRETER_FRAME_MONITORS_OFFSET - 1;
-  private static final int INTERPRETER_FRAME_METHOD_OFFSET = INTERPRETER_FRAME_LOCALS_OFFSET - 1;
+  private static final int INTERPRETER_FRAME_MIRROR_OFFSET = INTERPRETER_FRAME_LOCALS_OFFSET - 1;
+  private static final int INTERPRETER_FRAME_METHOD_OFFSET = INTERPRETER_FRAME_MIRROR_OFFSET - 1;
   private static final int INTERPRETER_FRAME_INITIAL_SP_OFFSET = INTERPRETER_FRAME_BCX_OFFSET - 1; // FIXME: probably wrong, but unused anyway
   private static final int INTERPRETER_FRAME_MONITOR_BLOCK_TOP_OFFSET = INTERPRETER_FRAME_INITIAL_SP_OFFSET;
   private static final int INTERPRETER_FRAME_MONITOR_BLOCK_BOTTOM_OFFSET = INTERPRETER_FRAME_INITIAL_SP_OFFSET;
--- a/hotspot/src/jdk.hotspot.agent/share/classes/sun/jvm/hotspot/runtime/sparc/SPARCFrame.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/src/jdk.hotspot.agent/share/classes/sun/jvm/hotspot/runtime/sparc/SPARCFrame.java	Mon Aug 29 08:53:32 2016 -0700
@@ -714,11 +714,7 @@
   /** 2 words, also used to save float regs across  calls to C */
   public static final int INTERPRETER_FRAME_D_SCRATCH_FP_OFFSET           = -2;
   public static final int INTERPRETER_FRAME_L_SCRATCH_FP_OFFSET           = -4;
-  /** For native calls only */
-  public static final int INTERPRETER_FRAME_PADDING_OFFSET                = -5;
-  /** For native calls only */
-  public static final int INTERPRETER_FRAME_MIRROR_OFFSET                 = -6;
-  /** Should be same as above, and should be zero mod 8 */
+  public static final int INTERPRETER_FRAME_MIRROR_OFFSET                 = -5;
   public static final int INTERPRETER_FRAME_VM_LOCALS_FP_OFFSET           = -6;
   public static final int INTERPRETER_FRAME_VM_LOCAL_WORDS                = -INTERPRETER_FRAME_VM_LOCALS_FP_OFFSET;
 
--- a/hotspot/src/jdk.hotspot.agent/share/classes/sun/jvm/hotspot/runtime/x86/X86Frame.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/src/jdk.hotspot.agent/share/classes/sun/jvm/hotspot/runtime/x86/X86Frame.java	Mon Aug 29 08:53:32 2016 -0700
@@ -48,10 +48,10 @@
   private static final int SENDER_SP_OFFSET           =  2;
 
   // Interpreter frames
-  private static final int INTERPRETER_FRAME_MIRROR_OFFSET    =  2; // for native calls only
   private static final int INTERPRETER_FRAME_SENDER_SP_OFFSET = -1;
   private static final int INTERPRETER_FRAME_LAST_SP_OFFSET   = INTERPRETER_FRAME_SENDER_SP_OFFSET - 1;
   private static final int INTERPRETER_FRAME_METHOD_OFFSET    = INTERPRETER_FRAME_LAST_SP_OFFSET - 1;
+  private static       int INTERPRETER_FRAME_MIRROR_OFFSET;
   private static       int INTERPRETER_FRAME_MDX_OFFSET;         // Non-core builds only
   private static       int INTERPRETER_FRAME_CACHE_OFFSET;
   private static       int INTERPRETER_FRAME_LOCALS_OFFSET;
@@ -74,7 +74,8 @@
   }
 
   private static synchronized void initialize(TypeDataBase db) {
-    INTERPRETER_FRAME_MDX_OFFSET                  = INTERPRETER_FRAME_METHOD_OFFSET - 1;
+    INTERPRETER_FRAME_MIRROR_OFFSET               = INTERPRETER_FRAME_METHOD_OFFSET - 1;
+    INTERPRETER_FRAME_MDX_OFFSET                  = INTERPRETER_FRAME_MIRROR_OFFSET - 1;
     INTERPRETER_FRAME_CACHE_OFFSET                = INTERPRETER_FRAME_MDX_OFFSET - 1;
     INTERPRETER_FRAME_LOCALS_OFFSET               = INTERPRETER_FRAME_CACHE_OFFSET - 1;
     INTERPRETER_FRAME_BCX_OFFSET                  = INTERPRETER_FRAME_LOCALS_OFFSET - 1;
--- a/hotspot/src/jdk.hotspot.agent/share/classes/sun/jvm/hotspot/utilities/ObjectReader.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/src/jdk.hotspot.agent/share/classes/sun/jvm/hotspot/utilities/ObjectReader.java	Mon Aug 29 08:53:32 2016 -0700
@@ -26,6 +26,7 @@
 
 import java.lang.reflect.Modifier;
 import java.util.*;
+import java.util.stream.*;
 import sun.jvm.hotspot.debugger.*;
 import sun.jvm.hotspot.oops.*;
 import sun.jvm.hotspot.runtime.*;
@@ -204,15 +205,29 @@
       }
    }
 
-   protected Object getHashtable(Instance oop, boolean isProperties) {
+   private void setPropertiesEntry(java.util.Properties p, Oop oop) {
+      InstanceKlass ik = (InstanceKlass)oop.getKlass();
+      OopField keyField = (OopField)ik.findField("key", "Ljava/lang/Object;");
+      OopField valueField = (OopField)ik.findField("val", "Ljava/lang/Object;");
+
+      try {
+         p.setProperty((String)readObject(keyField.getValue(oop)),
+                       (String)readObject(valueField.getValue(oop)));
+      } catch (ClassNotFoundException ce) {
+         if (DEBUG) {
+            debugPrintStackTrace(ce);
+         }
+      }
+   }
+
+   protected Object getHashtable(Instance oop) {
       InstanceKlass k = (InstanceKlass)oop.getKlass();
       OopField tableField = (OopField)k.findField("table", "[Ljava/util/Hashtable$Entry;");
       if (tableField == null) {
          debugPrintln("Could not find field of [Ljava/util/Hashtable$Entry;");
          return null;
       }
-      java.util.Hashtable table = (isProperties) ? new java.util.Properties()
-                                                 : new java.util.Hashtable();
+      java.util.Hashtable table = new java.util.Hashtable();
       ObjArray kvs = (ObjArray)tableField.getValue(oop);
       long size = kvs.getLength();
       debugPrintln("Hashtable$Entry Size = " + size);
@@ -225,6 +240,39 @@
       return table;
    }
 
+   private Properties getProperties(Instance oop) {
+      InstanceKlass k = (InstanceKlass)oop.getKlass();
+      OopField mapField = (OopField)k.findField("map", "Ljava/util/concurrent/ConcurrentHashMap;");
+      if (mapField == null) {
+         debugPrintln("Could not find field of Ljava/util/concurrent/ConcurrentHashMap");
+         return null;
+      }
+
+      Instance mapObj = (Instance)mapField.getValue(oop);
+      if (mapObj == null) {
+         debugPrintln("Could not get map field from java.util.Properties");
+         return null;
+      }
+
+      InstanceKlass mk = (InstanceKlass)mapObj.getKlass();
+      OopField tableField = (OopField)mk.findField("table", "[Ljava/util/concurrent/ConcurrentHashMap$Node;");
+      if (tableField == null) {
+         debugPrintln("Could not find field of [Ljava/util/concurrent/ConcurrentHashMap$Node");
+         return null;
+      }
+
+      java.util.Properties props = new java.util.Properties();
+      ObjArray kvs = (ObjArray)tableField.getValue(mapObj);
+      long size = kvs.getLength();
+      debugPrintln("ConcurrentHashMap$Node Size = " + size);
+      LongStream.range(0, size)
+                .mapToObj(kvs::getObjAt)
+                .filter(o -> o != null)
+                .forEach(o -> setPropertiesEntry(props, o));
+
+      return props;
+   }
+
    public Object readInstance(Instance oop) throws ClassNotFoundException {
       Object result = getFromObjTable(oop);
       if (result == null) {
@@ -240,11 +288,11 @@
          }
 
          if (kls.getName().equals(javaUtilHashtable())) {
-            return getHashtable(oop, false);
+            return getHashtable(oop);
          }
 
          if (kls.getName().equals(javaUtilProperties())) {
-            return getHashtable(oop, true);
+            return getProperties(oop);
          }
 
          Class clz = readClass(kls);
--- a/hotspot/src/jdk.vm.ci/share/classes/jdk.vm.ci.hotspot/src/jdk/vm/ci/hotspot/CompilerToVM.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/src/jdk.vm.ci/share/classes/jdk.vm.ci.hotspot/src/jdk/vm/ci/hotspot/CompilerToVM.java	Mon Aug 29 08:53:32 2016 -0700
@@ -265,9 +265,10 @@
     native HotSpotResolvedObjectTypeImpl resolveTypeInPool(HotSpotConstantPool constantPool, int cpi) throws LinkageError;
 
     /**
-     * Looks up and attempts to resolve the {@code JVM_CONSTANT_Field} entry for at index {@code cpi} in
-     * {@code constantPool}. For some opcodes, checks are performed that require the {@code method}
-     * that contains {@code opcode} to be specified. The values returned in {@code info} are:
+     * Looks up and attempts to resolve the {@code JVM_CONSTANT_Field} entry for at index
+     * {@code cpi} in {@code constantPool}. For some opcodes, checks are performed that require the
+     * {@code method} that contains {@code opcode} to be specified. The values returned in
+     * {@code info} are:
      *
      * <pre>
      *     [(int) flags,   // only valid if field is resolved
@@ -556,20 +557,18 @@
     native HotSpotResolvedJavaMethodImpl getResolvedJavaMethod(Object base, long displacement);
 
     /**
-     * Read a HotSpot ConstantPool* value from the memory location described by {@code base} plus
-     * {@code displacement} and return the {@link HotSpotConstantPool} wrapping it. This method does
-     * no checking that the memory location actually contains a valid pointer and may crash the VM
-     * if an invalid location is provided. If the {@code base} is null then {@code displacement} is
-     * used by itself. If {@code base} is a {@link HotSpotResolvedJavaMethodImpl},
-     * {@link HotSpotConstantPool} or {@link HotSpotResolvedObjectTypeImpl} then the metaspace
-     * pointer is fetched from that object and added to {@code displacement}. Any other non-null
-     * object type causes an {@link IllegalArgumentException} to be thrown.
+     * Gets the {@code ConstantPool*} associated with {@code object} and returns a
+     * {@link HotSpotConstantPool} wrapping it.
      *
-     * @param base an object to read from or null
-     * @param displacement
-     * @return null or the resolved method for this location
+     * @param object a {@link HotSpotResolvedJavaMethodImpl} or
+     *            {@link HotSpotResolvedObjectTypeImpl} object
+     * @return a {@link HotSpotConstantPool} wrapping the {@code ConstantPool*} associated with
+     *         {@code object}
+     * @throws NullPointerException if {@code object == null}
+     * @throws IllegalArgumentException if {@code object} is neither a
+     *             {@link HotSpotResolvedJavaMethodImpl} nor a {@link HotSpotResolvedObjectTypeImpl}
      */
-    native HotSpotConstantPool getConstantPool(Object base, long displacement);
+    native HotSpotConstantPool getConstantPool(Object object);
 
     /**
      * Read a HotSpot Klass* value from the memory location described by {@code base} plus
--- a/hotspot/src/jdk.vm.ci/share/classes/jdk.vm.ci.hotspot/src/jdk/vm/ci/hotspot/HotSpotResolvedJavaMethodImpl.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/src/jdk.vm.ci/share/classes/jdk.vm.ci.hotspot/src/jdk/vm/ci/hotspot/HotSpotResolvedJavaMethodImpl.java	Mon Aug 29 08:53:32 2016 -0700
@@ -121,7 +121,7 @@
         if (metaspaceConstantPool == holder.getConstantPool().getMetaspaceConstantPool()) {
             this.constantPool = holder.getConstantPool();
         } else {
-            this.constantPool = compilerToVM().getConstantPool(null, constMethod + config.constMethodConstantsOffset);
+            this.constantPool = compilerToVM().getConstantPool(this);
         }
 
         final int nameIndex = UNSAFE.getChar(constMethod + config.constMethodNameIndexOffset);
--- a/hotspot/src/jdk.vm.ci/share/classes/jdk.vm.ci.hotspot/src/jdk/vm/ci/hotspot/HotSpotResolvedObjectTypeImpl.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/src/jdk.vm.ci/share/classes/jdk.vm.ci.hotspot/src/jdk/vm/ci/hotspot/HotSpotResolvedObjectTypeImpl.java	Mon Aug 29 08:53:32 2016 -0700
@@ -445,7 +445,7 @@
              * operating on the latest one and that HotSpotResolvedJavaMethodImpls will be able to
              * use the shared copy instead of creating their own instance.
              */
-            constantPool = compilerToVM().getConstantPool(this, config().instanceKlassConstantsOffset);
+            constantPool = compilerToVM().getConstantPool(this);
         }
         return constantPool;
     }
--- a/hotspot/src/os/aix/vm/os_aix.cpp	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/src/os/aix/vm/os_aix.cpp	Mon Aug 29 08:53:32 2016 -0700
@@ -2686,7 +2686,8 @@
 //      - sets target osthread state to continue
 //      - sends signal to end the sigsuspend loop in the SR_handler
 //
-//  Note that the SR_lock plays no role in this suspend/resume protocol.
+//  Note that the SR_lock plays no role in this suspend/resume protocol,
+//  but is checked for NULL in SR_handler as a thread termination indicator.
 //
 
 static void resume_clear_context(OSThread *osthread) {
@@ -2718,9 +2719,22 @@
   // after sigsuspend.
   int old_errno = errno;
 
-  Thread* thread = Thread::current();
+  Thread* thread = Thread::current_or_null_safe();
+  assert(thread != NULL, "Missing current thread in SR_handler");
+
+  // On some systems we have seen signal delivery get "stuck" until the signal
+  // mask is changed as part of thread termination. Check that the current thread
+  // has not already terminated (via SR_lock()) - else the following assertion
+  // will fail because the thread is no longer a JavaThread as the ~JavaThread
+  // destructor has completed.
+
+  if (thread->SR_lock() == NULL) {
+    return;
+  }
+
+  assert(thread->is_VM_thread() || thread->is_Java_thread(), "Must be VMThread or JavaThread");
+
   OSThread* osthread = thread->osthread();
-  assert(thread->is_VM_thread() || thread->is_Java_thread(), "Must be VMThread or JavaThread");
 
   os::SuspendResume::State current = osthread->sr.state();
   if (current == os::SuspendResume::SR_SUSPEND_REQUEST) {
--- a/hotspot/src/os/bsd/vm/os_bsd.cpp	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/src/os/bsd/vm/os_bsd.cpp	Mon Aug 29 08:53:32 2016 -0700
@@ -2716,7 +2716,8 @@
 //      - sets target osthread state to continue
 //      - sends signal to end the sigsuspend loop in the SR_handler
 //
-//  Note that the SR_lock plays no role in this suspend/resume protocol.
+//  Note that the SR_lock plays no role in this suspend/resume protocol,
+//  but is checked for NULL in SR_handler as a thread termination indicator.
 
 static void resume_clear_context(OSThread *osthread) {
   osthread->set_ucontext(NULL);
@@ -2746,9 +2747,22 @@
   // after sigsuspend.
   int old_errno = errno;
 
-  Thread* thread = Thread::current();
+  Thread* thread = Thread::current_or_null_safe();
+  assert(thread != NULL, "Missing current thread in SR_handler");
+
+  // On some systems we have seen signal delivery get "stuck" until the signal
+  // mask is changed as part of thread termination. Check that the current thread
+  // has not already terminated (via SR_lock()) - else the following assertion
+  // will fail because the thread is no longer a JavaThread as the ~JavaThread
+  // destructor has completed.
+
+  if (thread->SR_lock() == NULL) {
+    return;
+  }
+
+  assert(thread->is_VM_thread() || thread->is_Java_thread(), "Must be VMThread or JavaThread");
+
   OSThread* osthread = thread->osthread();
-  assert(thread->is_VM_thread() || thread->is_Java_thread(), "Must be VMThread or JavaThread");
 
   os::SuspendResume::State current = osthread->sr.state();
   if (current == os::SuspendResume::SR_SUSPEND_REQUEST) {
--- a/hotspot/src/os/linux/vm/os_linux.cpp	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/src/os/linux/vm/os_linux.cpp	Mon Aug 29 08:53:32 2016 -0700
@@ -3971,7 +3971,8 @@
 //      - sets target osthread state to continue
 //      - sends signal to end the sigsuspend loop in the SR_handler
 //
-//  Note that the SR_lock plays no role in this suspend/resume protocol.
+//  Note that the SR_lock plays no role in this suspend/resume protocol,
+//  but is checked for NULL in SR_handler as a thread termination indicator.
 
 static void resume_clear_context(OSThread *osthread) {
   osthread->set_ucontext(NULL);
@@ -4004,8 +4005,20 @@
 
   Thread* thread = Thread::current_or_null_safe();
   assert(thread != NULL, "Missing current thread in SR_handler");
+
+  // On some systems we have seen signal delivery get "stuck" until the signal
+  // mask is changed as part of thread termination. Check that the current thread
+  // has not already terminated (via SR_lock()) - else the following assertion
+  // will fail because the thread is no longer a JavaThread as the ~JavaThread
+  // destructor has completed.
+
+  if (thread->SR_lock() == NULL) {
+    return;
+  }
+
+  assert(thread->is_VM_thread() || thread->is_Java_thread(), "Must be VMThread or JavaThread");
+
   OSThread* osthread = thread->osthread();
-  assert(thread->is_VM_thread() || thread->is_Java_thread(), "Must be VMThread or JavaThread");
 
   os::SuspendResume::State current = osthread->sr.state();
   if (current == os::SuspendResume::SR_SUSPEND_REQUEST) {
--- a/hotspot/src/os/posix/vm/os_posix.cpp	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/src/os/posix/vm/os_posix.cpp	Mon Aug 29 08:53:32 2016 -0700
@@ -93,10 +93,6 @@
 }
 
 int os::get_native_stack(address* stack, int frames, int toSkip) {
-#ifdef _NMT_NOINLINE_
-  toSkip++;
-#endif
-
   int frame_idx = 0;
   int num_of_frames;  // number of frames captured
   frame fr = os::current_frame();
--- a/hotspot/src/os/windows/vm/os_windows.cpp	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/src/os/windows/vm/os_windows.cpp	Mon Aug 29 08:53:32 2016 -0700
@@ -318,9 +318,6 @@
 // only supported on Windows XP or later.
 //
 int os::get_native_stack(address* stack, int frames, int toSkip) {
-#ifdef _NMT_NOINLINE_
-  toSkip++;
-#endif
   int captured = RtlCaptureStackBackTrace(toSkip + 1, frames, (PVOID*)stack, NULL);
   for (int index = captured; index < frames; index ++) {
     stack[index] = NULL;
--- a/hotspot/src/os_cpu/bsd_x86/vm/os_bsd_x86.cpp	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/src/os_cpu/bsd_x86/vm/os_bsd_x86.cpp	Mon Aug 29 08:53:32 2016 -0700
@@ -417,7 +417,15 @@
 #else
   register intptr_t **ebp __asm__ (SPELL_REG_FP);
 #endif
-  return (intptr_t*) *ebp;   // we want what it points to.
+  // ebp is for this frame (_get_previous_fp). We want the ebp for the
+  // caller of os::current_frame*(), so go up two frames. However, for
+  // optimized builds, _get_previous_fp() will be inlined, so only go
+  // up 1 frame in that case.
+#ifdef _NMT_NOINLINE_
+  return **(intptr_t***)ebp;
+#else
+  return *ebp;
+#endif
 }
 
 
--- a/hotspot/src/os_cpu/linux_ppc/vm/os_linux_ppc.cpp	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/src/os_cpu/linux_ppc/vm/os_linux_ppc.cpp	Mon Aug 29 08:53:32 2016 -0700
@@ -238,6 +238,28 @@
     }
   }
 
+  // Make the signal handler transaction-aware by checking the existence of a
+  // second (transactional) context with MSR TS bits active. If the signal is
+  // caught during a transaction, then just return to the HTM abort handler.
+  // Please refer to Linux kernel document powerpc/transactional_memory.txt,
+  // section "Signals".
+  if (uc && uc->uc_link) {
+    ucontext_t* second_uc = uc->uc_link;
+
+    // MSR TS bits are 29 and 30 (Power ISA, v2.07B, Book III-S, pp. 857-858,
+    // 3.2.1 "Machine State Register"), however note that ISA notation for bit
+    // numbering is MSB 0, so for normal bit numbering (LSB 0) they come to be
+    // bits 33 and 34. It's not related to endianness, just a notation matter.
+    if (second_uc->uc_mcontext.regs->msr & 0x600000000) {
+      if (TraceTraps) {
+        tty->print_cr("caught signal in transaction, "
+                        "ignoring to jump to abort handler");
+      }
+      // Return control to the HTM abort handler.
+      return true;
+    }
+  }
+
   JavaThread* thread = NULL;
   VMThread* vmthread = NULL;
   if (os::Linux::signal_handlers_are_installed) {
--- a/hotspot/src/os_cpu/linux_x86/vm/os_linux_x86.cpp	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/src/os_cpu/linux_x86/vm/os_linux_x86.cpp	Mon Aug 29 08:53:32 2016 -0700
@@ -235,7 +235,15 @@
 #else
   register intptr_t **ebp __asm__ (SPELL_REG_FP);
 #endif
-  return (intptr_t*) *ebp;   // we want what it points to.
+  // ebp is for this frame (_get_previous_fp). We want the ebp for the
+  // caller of os::current_frame*(), so go up two frames. However, for
+  // optimized builds, _get_previous_fp() will be inlined, so only go
+  // up 1 frame in that case.
+#ifdef _NMT_NOINLINE_
+  return **(intptr_t***)ebp;
+#else
+  return *ebp;
+#endif
 }
 
 
--- a/hotspot/src/os_cpu/solaris_x86/vm/os_solaris_x86.cpp	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/src/os_cpu/solaris_x86/vm/os_solaris_x86.cpp	Mon Aug 29 08:53:32 2016 -0700
@@ -292,15 +292,19 @@
 
 frame os::current_frame() {
   intptr_t* fp = _get_current_fp();  // it's inlined so want current fp
+  // fp is for os::current_frame. We want the fp for our caller.
   frame myframe((intptr_t*)os::current_stack_pointer(),
                 (intptr_t*)fp,
                 CAST_FROM_FN_PTR(address, os::current_frame));
-  if (os::is_first_C_frame(&myframe)) {
+  frame caller_frame = os::get_sender_for_C_frame(&myframe);
+
+  if (os::is_first_C_frame(&caller_frame)) {
     // stack is not walkable
     frame ret; // This will be a null useless frame
     return ret;
   } else {
-    return os::get_sender_for_C_frame(&myframe);
+    // return frame for our caller's caller
+    return os::get_sender_for_C_frame(&caller_frame);
   }
 }
 
--- a/hotspot/src/os_cpu/windows_x86/vm/os_windows_x86.cpp	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/src/os_cpu/windows_x86/vm/os_windows_x86.cpp	Mon Aug 29 08:53:32 2016 -0700
@@ -496,7 +496,15 @@
   __asm {
     mov frameptr, ebp
   };
+  // ebp (frameptr) is for this frame (_get_previous_fp). We want the ebp for the
+  // caller of os::current_frame*(), so go up two frames. However, for
+  // optimized builds, _get_previous_fp() will be inlined, so only go
+  // up 1 frame in that case.
+#ifdef _NMT_NOINLINE_
+  return **(intptr_t***)frameptr;
+#else
   return *frameptr;
+#endif
 }
 #endif // !AMD64
 
--- a/hotspot/src/share/vm/classfile/classLoaderData.cpp	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/src/share/vm/classfile/classLoaderData.cpp	Mon Aug 29 08:53:32 2016 -0700
@@ -126,13 +126,17 @@
 // ClassLoaderData, no other non-GC thread has knowledge of the anonymous class while
 // it is being defined, therefore _keep_alive is not volatile or atomic.
 void ClassLoaderData::inc_keep_alive() {
-  assert(_keep_alive >= 0, "Invalid keep alive count");
-  _keep_alive++;
+  if (is_anonymous()) {
+    assert(_keep_alive >= 0, "Invalid keep alive increment count");
+    _keep_alive++;
+  }
 }
 
 void ClassLoaderData::dec_keep_alive() {
-  assert(_keep_alive > 0, "Invalid keep alive count");
-  _keep_alive--;
+  if (is_anonymous()) {
+    assert(_keep_alive > 0, "Invalid keep alive decrement count");
+    _keep_alive--;
+  }
 }
 
 void ClassLoaderData::oops_do(OopClosure* f, KlassClosure* klass_closure, bool must_claim) {
@@ -1173,7 +1177,7 @@
   if (class_loader() == NULL) {
     out->print("NULL class_loader");
   } else {
-    out->print("class loader " INTPTR_FORMAT, p2i(this));
+    out->print("class loader " INTPTR_FORMAT " ", p2i(this));
     class_loader()->print_value_on(out);
   }
 }
--- a/hotspot/src/share/vm/classfile/classLoaderData.hpp	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/src/share/vm/classfile/classLoaderData.hpp	Mon Aug 29 08:53:32 2016 -0700
@@ -176,9 +176,9 @@
   Mutex* _metaspace_lock;  // Locks the metaspace for allocations and setup.
   bool _unloading;         // true if this class loader goes away
   bool _is_anonymous;      // if this CLD is for an anonymous class
-  int _keep_alive;         // if this CLD is kept alive without a keep_alive_object().
-                           // Currently used solely for anonymous classes.
-                           // _keep_alive does not need to be volatile or
+  s2 _keep_alive;          // if this CLD is kept alive without a keep_alive_object().
+                           // Used for anonymous classes and the boot class
+                           // loader. _keep_alive does not need to be volatile or
                            // atomic since there is one unique CLD per anonymous class.
   volatile int _claimed;   // true if claimed, for example during GC traces.
                            // To avoid applying oop closure more than once.
@@ -289,6 +289,8 @@
     return _unloading;
   }
 
+  // Used to refcount an anonymous class's CLD in order to
+  // indicate their aliveness without a keep_alive_object().
   void inc_keep_alive();
   void dec_keep_alive();
 
--- a/hotspot/src/share/vm/code/dependencies.cpp	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/src/share/vm/code/dependencies.cpp	Mon Aug 29 08:53:32 2016 -0700
@@ -1082,12 +1082,11 @@
     if (!(m->is_public() || m->is_protected()))
       // The override story is complex when packages get involved.
       return true;  // Must punt the assertion to true.
-    Klass* k = ctxk;
-    Method* lm = k->lookup_method(m->name(), m->signature());
-    if (lm == NULL && k->is_instance_klass()) {
+    Method* lm = ctxk->lookup_method(m->name(), m->signature());
+    if (lm == NULL && ctxk->is_instance_klass()) {
       // It might be an interface method
-      lm = InstanceKlass::cast(k)->lookup_method_in_ordered_interfaces(m->name(),
-                                                                 m->signature());
+      lm = InstanceKlass::cast(ctxk)->lookup_method_in_ordered_interfaces(m->name(),
+                                                                          m->signature());
     }
     if (lm == m)
       // Method m is inherited into ctxk.
@@ -1101,11 +1100,19 @@
         // Static methods don't override non-static so punt
         return true;
       }
-      if (   !Dependencies::is_concrete_method(lm, k)
-          && !Dependencies::is_concrete_method(m, ctxk)
-          && lm->method_holder()->is_subtype_of(m->method_holder()))
-        // Method m is overridden by lm, but both are non-concrete.
-        return true;
+      if (!Dependencies::is_concrete_method(lm, ctxk) &&
+          !Dependencies::is_concrete_method(m, ctxk)) {
+        // They are both non-concrete
+        if (lm->method_holder()->is_subtype_of(m->method_holder())) {
+          // Method m is overridden by lm, but both are non-concrete.
+          return true;
+        }
+        if (lm->method_holder()->is_interface() && m->method_holder()->is_interface() &&
+            ctxk->is_subtype_of(m->method_holder()) && ctxk->is_subtype_of(lm->method_holder())) {
+          // Interface method defined in multiple super interfaces
+          return true;
+        }
+      }
     }
     ResourceMark rm;
     tty->print_cr("Dependency method not found in the associated context:");
--- a/hotspot/src/share/vm/gc/g1/g1Analytics.cpp	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/src/share/vm/gc/g1/g1Analytics.cpp	Mon Aug 29 08:53:32 2016 -0700
@@ -316,8 +316,12 @@
   return get_new_size_prediction(_pending_cards_seq);
 }
 
+double G1Analytics::oldest_known_gc_end_time_sec() const {
+  return _recent_prev_end_times_for_all_gcs_sec->oldest();
+}
+
 double G1Analytics::last_known_gc_end_time_sec() const {
-  return _recent_prev_end_times_for_all_gcs_sec->oldest();
+  return _recent_prev_end_times_for_all_gcs_sec->last();
 }
 
 void G1Analytics::update_recent_gc_times(double end_time_sec,
--- a/hotspot/src/share/vm/gc/g1/g1Analytics.hpp	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/src/share/vm/gc/g1/g1Analytics.hpp	Mon Aug 29 08:53:32 2016 -0700
@@ -155,6 +155,7 @@
   void update_recent_gc_times(double end_time_sec, double elapsed_ms);
   void compute_pause_time_ratio(double interval_ms, double pause_time_ms);
 
+  double oldest_known_gc_end_time_sec() const;
   double last_known_gc_end_time_sec() const;
 };
 
--- a/hotspot/src/share/vm/gc/g1/g1CollectedHeap.cpp	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/src/share/vm/gc/g1/g1CollectedHeap.cpp	Mon Aug 29 08:53:32 2016 -0700
@@ -28,6 +28,7 @@
 #include "classfile/symbolTable.hpp"
 #include "code/codeCache.hpp"
 #include "code/icBuffer.hpp"
+#include "gc/g1/g1Analytics.hpp"
 #include "gc/g1/bufferingOopClosure.hpp"
 #include "gc/g1/concurrentG1Refine.hpp"
 #include "gc/g1/concurrentG1RefineThread.hpp"
@@ -2473,8 +2474,19 @@
 }
 
 jlong G1CollectedHeap::millis_since_last_gc() {
-  // assert(false, "NYI");
-  return 0;
+  jlong now = os::elapsed_counter() / NANOSECS_PER_MILLISEC;
+  const G1Analytics* analytics = _g1_policy->analytics();
+  double last = analytics->last_known_gc_end_time_sec();
+  jlong ret_val = now - (last * 1000);
+  if (ret_val < 0) {
+    // See the notes in GenCollectedHeap::millis_since_last_gc()
+    // for more information about the implementation.
+    log_warning(gc)("Detected clock going backwards. "
+      "Milliseconds since last GC would be " JLONG_FORMAT
+      ". returning zero instead.", ret_val);
+    return 0;
+  }
+  return ret_val;
 }
 
 void G1CollectedHeap::prepare_for_verify() {
--- a/hotspot/src/share/vm/gc/g1/g1DefaultPolicy.cpp	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/src/share/vm/gc/g1/g1DefaultPolicy.cpp	Mon Aug 29 08:53:32 2016 -0700
@@ -604,7 +604,7 @@
     _analytics->report_alloc_rate_ms(alloc_rate_ms);
 
     double interval_ms =
-      (end_time_sec - _analytics->last_known_gc_end_time_sec()) * 1000.0;
+      (end_time_sec - _analytics->oldest_known_gc_end_time_sec()) * 1000.0;
     _analytics->update_recent_gc_times(end_time_sec, pause_time_ms);
     _analytics->compute_pause_time_ratio(interval_ms, pause_time_ms);
   }
--- a/hotspot/src/share/vm/gc/shared/genCollectedHeap.cpp	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/src/share/vm/gc/shared/genCollectedHeap.cpp	Mon Aug 29 08:53:32 2016 -0700
@@ -1256,21 +1256,21 @@
 };
 
 jlong GenCollectedHeap::millis_since_last_gc() {
-  // We need a monotonically non-decreasing time in ms but
-  // os::javaTimeMillis() does not guarantee monotonicity.
+  // javaTimeNanos() is guaranteed to be monotonically non-decreasing
+  // provided the underlying platform provides such a time source
+  // (and it is bug free). So we still have to guard against getting
+  // back a time later than 'now'.
   jlong now = os::javaTimeNanos() / NANOSECS_PER_MILLISEC;
   GenTimeOfLastGCClosure tolgc_cl(now);
   // iterate over generations getting the oldest
   // time that a generation was collected
   generation_iterate(&tolgc_cl, false);
 
-  // javaTimeNanos() is guaranteed to be monotonically non-decreasing
-  // provided the underlying platform provides such a time source
-  // (and it is bug free). So we still have to guard against getting
-  // back a time later than 'now'.
   jlong retVal = now - tolgc_cl.time();
   if (retVal < 0) {
-    NOT_PRODUCT(log_warning(gc)("time warp: " JLONG_FORMAT, retVal);)
+    log_warning(gc)("Detected clock going backwards. "
+      "Milliseconds since last GC would be " JLONG_FORMAT
+      ". returning zero instead.", retVal);
     return 0;
   }
   return retVal;
--- a/hotspot/src/share/vm/jvmci/jvmciCompilerToVM.cpp	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/src/share/vm/jvmci/jvmciCompilerToVM.cpp	Mon Aug 29 08:53:32 2016 -0700
@@ -461,31 +461,26 @@
   return JNIHandles::make_local(THREAD, result);
 }
 
-C2V_VMENTRY(jobject, getConstantPool, (JNIEnv *, jobject, jobject base, jlong offset))
+C2V_VMENTRY(jobject, getConstantPool, (JNIEnv *, jobject, jobject object_handle))
   constantPoolHandle cp;
-  oop base_object = JNIHandles::resolve(base);
-  jlong base_address = 0;
-  if (base_object != NULL) {
-    if (base_object->is_a(SystemDictionary::HotSpotResolvedJavaMethodImpl_klass())) {
-      base_address = HotSpotResolvedJavaMethodImpl::metaspaceMethod(base_object);
-    } else if (base_object->is_a(SystemDictionary::HotSpotConstantPool_klass())) {
-      base_address = HotSpotConstantPool::metaspaceConstantPool(base_object);
-    } else if (base_object->is_a(SystemDictionary::HotSpotResolvedObjectTypeImpl_klass())) {
-      base_address = (jlong) CompilerToVM::asKlass(base_object);
-    } else {
-      THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
-                  err_msg("Unexpected type: %s", base_object->klass()->external_name()));
-    }
+  oop object = JNIHandles::resolve(object_handle);
+  if (object == NULL) {
+    THROW_0(vmSymbols::java_lang_NullPointerException());
   }
-  cp = *((ConstantPool**) (intptr_t) (base_address + offset));
-  if (!cp.is_null()) {
-    JavaValue method_result(T_OBJECT);
-    JavaCallArguments args;
-    args.push_long((jlong) (address) cp());
-    JavaCalls::call_static(&method_result, SystemDictionary::HotSpotConstantPool_klass(), vmSymbols::fromMetaspace_name(), vmSymbols::constantPool_fromMetaspace_signature(), &args, CHECK_NULL);
-    return JNIHandles::make_local(THREAD, (oop)method_result.get_jobject());
+  if (object->is_a(SystemDictionary::HotSpotResolvedJavaMethodImpl_klass())) {
+    cp = CompilerToVM::asMethod(object)->constMethod()->constants();
+  } else if (object->is_a(SystemDictionary::HotSpotResolvedObjectTypeImpl_klass())) {
+    cp = InstanceKlass::cast(CompilerToVM::asKlass(object))->constants();
+  } else {
+    THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
+                err_msg("Unexpected type: %s", object->klass()->external_name()));
   }
-  return NULL;
+  assert(!cp.is_null(), "npe");
+  JavaValue method_result(T_OBJECT);
+  JavaCallArguments args;
+  args.push_long((jlong) (address) cp());
+  JavaCalls::call_static(&method_result, SystemDictionary::HotSpotConstantPool_klass(), vmSymbols::fromMetaspace_name(), vmSymbols::constantPool_fromMetaspace_signature(), &args, CHECK_NULL);
+  return JNIHandles::make_local(THREAD, (oop)method_result.get_jobject());
 }
 
 C2V_VMENTRY(jobject, getResolvedJavaType, (JNIEnv *, jobject, jobject base, jlong offset, jboolean compressed))
@@ -1522,7 +1517,7 @@
   {CC "getMaxCallTargetOffset",                       CC "(J)J",                                                                            FN_PTR(getMaxCallTargetOffset)},
   {CC "getResolvedJavaMethodAtSlot",                  CC "(" CLASS "I)" HS_RESOLVED_METHOD,                                                 FN_PTR(getResolvedJavaMethodAtSlot)},
   {CC "getResolvedJavaMethod",                        CC "(Ljava/lang/Object;J)" HS_RESOLVED_METHOD,                                        FN_PTR(getResolvedJavaMethod)},
-  {CC "getConstantPool",                              CC "(Ljava/lang/Object;J)" HS_CONSTANT_POOL,                                          FN_PTR(getConstantPool)},
+  {CC "getConstantPool",                              CC "(Ljava/lang/Object;)" HS_CONSTANT_POOL,                                           FN_PTR(getConstantPool)},
   {CC "getResolvedJavaType",                          CC "(Ljava/lang/Object;JZ)" HS_RESOLVED_KLASS,                                        FN_PTR(getResolvedJavaType)},
   {CC "readConfiguration",                            CC "()[" OBJECT,                                                                      FN_PTR(readConfiguration)},
   {CC "installCode",                                  CC "(" TARGET_DESCRIPTION HS_COMPILED_CODE INSTALLED_CODE HS_SPECULATION_LOG ")I",    FN_PTR(installCode)},
--- a/hotspot/src/share/vm/logging/logTagSet.hpp	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/src/share/vm/logging/logTagSet.hpp	Mon Aug 29 08:53:32 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, 2016 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/hotspot/src/share/vm/oops/methodCounters.hpp	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/src/share/vm/oops/methodCounters.hpp	Mon Aug 29 08:53:32 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, 2016 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
--- a/hotspot/src/share/vm/opto/arraycopynode.cpp	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/src/share/vm/opto/arraycopynode.cpp	Mon Aug 29 08:53:32 2016 -0700
@@ -630,6 +630,12 @@
 }
 
 bool ArrayCopyNode::may_modify_helper(const TypeOopPtr *t_oop, Node* n, PhaseTransform *phase, ArrayCopyNode*& ac) {
+  if (n->Opcode() == Op_StoreCM ||
+      n->Opcode() == Op_StoreB) {
+    // Ignore card mark stores
+    n = n->in(MemNode::Memory);
+  }
+
   if (n->is_Proj()) {
     n = n->in(0);
     if (n->is_Call() && n->as_Call()->may_modify(t_oop, phase)) {
@@ -657,9 +663,6 @@
           }
         }
       }
-    } else if (n->Opcode() == Op_StoreCM) {
-      // Ignore card mark stores
-      return may_modify_helper(t_oop, n->in(MemNode::Memory), phase, ac);
     }
   }
 
--- a/hotspot/src/share/vm/opto/cfgnode.cpp	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/src/share/vm/opto/cfgnode.cpp	Mon Aug 29 08:53:32 2016 -0700
@@ -1703,29 +1703,51 @@
     }
 
     if (uncasted) {
-      // Add a cast node between the phi to be removed and its unique input.
+      // Add cast nodes between the phi to be removed and its unique input.
       // Wait until after parsing for the type information to propagate from the casts.
       assert(can_reshape, "Invalid during parsing");
       const Type* phi_type = bottom_type();
       assert(phi_type->isa_int() || phi_type->isa_ptr(), "bad phi type");
-      int opcode;
-      // Determine the type of cast to be added.
+      // Add casts to carry the control dependency of the Phi that is
+      // going away
+      Node* cast = NULL;
       if (phi_type->isa_int()) {
-        opcode = Op_CastII;
+        cast = ConstraintCastNode::make_cast(Op_CastII, r, uin, phi_type, true);
       } else {
         const Type* uin_type = phase->type(uin);
-        if ((phi_type->join(TypePtr::NOTNULL) == uin_type->join(TypePtr::NOTNULL)) ||
-            (!phi_type->isa_oopptr() && !uin_type->isa_oopptr())) {
-          opcode = Op_CastPP;
+        if (!phi_type->isa_oopptr() && !uin_type->isa_oopptr()) {
+          cast = ConstraintCastNode::make_cast(Op_CastPP, r, uin, phi_type, true);
         } else {
-          opcode = Op_CheckCastPP;
+          // Use a CastPP for a cast to not null and a CheckCastPP for
+          // a cast to a new klass (and both if both null-ness and
+          // klass change).
+
+          // If the type of phi is not null but the type of uin may be
+          // null, uin's type must be casted to not null
+          if (phi_type->join(TypePtr::NOTNULL) == phi_type->remove_speculative() &&
+              uin_type->join(TypePtr::NOTNULL) != uin_type->remove_speculative()) {
+            cast = ConstraintCastNode::make_cast(Op_CastPP, r, uin, TypePtr::NOTNULL, true);
+          }
+
+          // If the type of phi and uin, both casted to not null,
+          // differ the klass of uin must be (check)cast'ed to match
+          // that of phi
+          if (phi_type->join_speculative(TypePtr::NOTNULL) != uin_type->join_speculative(TypePtr::NOTNULL)) {
+            Node* n = uin;
+            if (cast != NULL) {
+              cast = phase->transform(cast);
+              n = cast;
+            }
+            cast = ConstraintCastNode::make_cast(Op_CheckCastPP, r, n, phi_type, true);
+          }
+          if (cast == NULL) {
+            cast = ConstraintCastNode::make_cast(Op_CastPP, r, uin, phi_type, true);
+          }
         }
       }
-      // Add a cast to carry the control dependency of the Phi that is
-      // going away
-      Node* cast = ConstraintCastNode::make_cast(opcode, r, uin, phi_type, true);
+      assert(cast != NULL, "cast should be set");
       cast = phase->transform(cast);
-      // set all inputs to the new cast so the Phi is removed by Identity
+      // set all inputs to the new cast(s) so the Phi is removed by Identity
       PhaseIterGVN* igvn = phase->is_IterGVN();
       for (uint i = 1; i < req(); i++) {
         set_req_X(i, cast, igvn);
--- a/hotspot/src/share/vm/prims/unsafe.cpp	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/src/share/vm/prims/unsafe.cpp	Mon Aug 29 08:53:32 2016 -0700
@@ -861,6 +861,13 @@
   }
 
   const Klass* host_klass = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(host_class));
+
+  // Make sure it's the real host class, not another anonymous class.
+  while (host_klass != NULL && host_klass->is_instance_klass() &&
+         InstanceKlass::cast(host_klass)->is_anonymous()) {
+    host_klass = InstanceKlass::cast(host_klass)->host_klass();
+  }
+
   // Primitive types have NULL Klass* fields in their java.lang.Class instances.
   if (host_klass == NULL) {
     THROW_0(vmSymbols::java_lang_IllegalArgumentException());
--- a/hotspot/src/share/vm/prims/whitebox.cpp	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/src/share/vm/prims/whitebox.cpp	Mon Aug 29 08:53:32 2016 -0700
@@ -679,7 +679,7 @@
 WB_END
 
 WB_ENTRY(jboolean, WB_IsIntrinsicAvailable(JNIEnv* env, jobject o, jobject method, jobject compilation_context, jint compLevel))
-  if (compLevel < CompLevel_none || compLevel > CompLevel_highest_tier) {
+  if (compLevel < CompLevel_none || compLevel > MIN2((CompLevel) TieredStopAtLevel, CompLevel_highest_tier)) {
     return false; // Intrinsic is not available on a non-existent compilation level.
   }
   jmethodID method_id, compilation_context_id;
@@ -689,6 +689,7 @@
 
   DirectiveSet* directive;
   AbstractCompiler* comp = CompileBroker::compiler((int)compLevel);
+  assert(comp != NULL, "compiler not available");
   if (compilation_context != NULL) {
     compilation_context_id = reflected_method_to_jmid(thread, env, compilation_context);
     CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
@@ -698,7 +699,7 @@
     // Calling with NULL matches default directive
     directive = DirectivesStack::getDefaultDirective(comp);
   }
-  bool result = CompileBroker::compiler(compLevel)->is_intrinsic_available(mh, directive);
+  bool result = comp->is_intrinsic_available(mh, directive);
   DirectivesStack::release(directive);
   return result;
 WB_END
--- a/hotspot/src/share/vm/runtime/advancedThresholdPolicy.cpp	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/src/share/vm/runtime/advancedThresholdPolicy.cpp	Mon Aug 29 08:53:32 2016 -0700
@@ -55,7 +55,8 @@
     // Simple log n seems to grow too slowly for tiered, try something faster: log n * log log n
     int log_cpu = log2_intptr(os::active_processor_count());
     int loglog_cpu = log2_intptr(MAX2(log_cpu, 1));
-    count = MAX2(log_cpu * loglog_cpu, 1) * 3 / 2;
+    count = MAX2(log_cpu * loglog_cpu * 3 / 2, 2);
+    FLAG_SET_ERGO(intx, CICompilerCount, count);
   }
 #else
   // On 32-bit systems, the number of compiler threads is limited to 3.
@@ -67,12 +68,18 @@
   /// available to the VM and thus cause the VM to crash.
   if (FLAG_IS_DEFAULT(CICompilerCount)) {
     count = 3;
+    FLAG_SET_ERGO(intx, CICompilerCount, count);
   }
 #endif
 
-  set_c1_count(MAX2(count / 3, 1));
-  set_c2_count(MAX2(count - c1_count(), 1));
-  FLAG_SET_ERGO(intx, CICompilerCount, c1_count() + c2_count());
+  if (TieredStopAtLevel < CompLevel_full_optimization) {
+    // No C2 compiler thread required
+    set_c1_count(count);
+  } else {
+    set_c1_count(MAX2(count / 3, 1));
+    set_c2_count(MAX2(count - c1_count(), 1));
+  }
+  assert(count == c1_count() + c2_count(), "inconsistent compiler thread count");
 
   // Some inlining tuning
 #ifdef X86
--- a/hotspot/src/share/vm/runtime/frame.cpp	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/src/share/vm/runtime/frame.cpp	Mon Aug 29 08:53:32 2016 -0700
@@ -225,6 +225,19 @@
   return NULL;
 }
 
+bool frame::is_entry_frame_valid(JavaThread* thread) const {
+  // Validate the JavaCallWrapper an entry frame must have
+  address jcw = (address)entry_frame_call_wrapper();
+  bool jcw_safe = (jcw < thread->stack_base()) && (jcw > (address)fp()); // less than stack base
+  if (!jcw_safe) {
+    return false;
+  }
+
+  // Validate sp saved in the java frame anchor
+  JavaFrameAnchor* jfa = entry_frame_call_wrapper()->anchor();
+  return (jfa->last_Java_sp() > sp());
+}
+
 bool frame::should_be_deoptimized() const {
   if (_deopt_state == is_deoptimized ||
       !is_compiled_frame() ) return false;
--- a/hotspot/src/share/vm/runtime/frame.hpp	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/src/share/vm/runtime/frame.hpp	Mon Aug 29 08:53:32 2016 -0700
@@ -166,6 +166,8 @@
   frame sender_for_interpreter_frame(RegisterMap* map) const;
   frame sender_for_native_frame(RegisterMap* map) const;
 
+  bool is_entry_frame_valid(JavaThread* thread) const;
+
   // All frames:
 
   // A low-level interface for vframes:
--- a/hotspot/src/share/vm/runtime/globals.hpp	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/src/share/vm/runtime/globals.hpp	Mon Aug 29 08:53:32 2016 -0700
@@ -2411,7 +2411,7 @@
   product(intx, CICompilerCount, CI_COMPILER_COUNT,                         \
           "Number of compiler threads to run")                              \
           range(0, max_jint)                                                \
-          constraint(CICompilerCountConstraintFunc, AtParse)                \
+          constraint(CICompilerCountConstraintFunc, AfterErgo)              \
                                                                             \
   product(intx, CompilationPolicyChoice, 0,                                 \
           "which compilation policy (0-3)")                                 \
--- a/hotspot/src/share/vm/runtime/reflection.cpp	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/src/share/vm/runtime/reflection.cpp	Mon Aug 29 08:53:32 2016 -0700
@@ -660,11 +660,13 @@
   }
 
   const Klass* host_class = current_class;
-  while (host_class->is_instance_klass() &&
-         InstanceKlass::cast(host_class)->is_anonymous()) {
-    const Klass* next_host_class = InstanceKlass::cast(host_class)->host_klass();
-    if (next_host_class == NULL)  break;
-    host_class = next_host_class;
+  if (host_class->is_instance_klass() &&
+      InstanceKlass::cast(host_class)->is_anonymous()) {
+    host_class = InstanceKlass::cast(host_class)->host_klass();
+    assert(host_class != NULL, "Anonymous class has null host class");
+    assert(!(host_class->is_instance_klass() &&
+           InstanceKlass::cast(host_class)->is_anonymous()),
+           "host_class should not be anonymous");
   }
   if (host_class == field_class) {
     return true;
--- a/hotspot/src/share/vm/runtime/simpleThresholdPolicy.cpp	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/src/share/vm/runtime/simpleThresholdPolicy.cpp	Mon Aug 29 08:53:32 2016 -0700
@@ -147,12 +147,18 @@
   // performed on 32-bit systems because it can lead to exhaustion
   // of the virtual memory address space available to the JVM.
   if (CICompilerCountPerCPU) {
-    count = MAX2(log2_intptr(os::active_processor_count()), 1) * 3 / 2;
+    count = MAX2(log2_intptr(os::active_processor_count()) * 3 / 2, 2);
+    FLAG_SET_ERGO(intx, CICompilerCount, count);
   }
 #endif
-  set_c1_count(MAX2(count / 3, 1));
-  set_c2_count(MAX2(count - c1_count(), 1));
-  FLAG_SET_ERGO(intx, CICompilerCount, c1_count() + c2_count());
+  if (TieredStopAtLevel < CompLevel_full_optimization) {
+    // No C2 compiler thread required
+    set_c1_count(count);
+  } else {
+    set_c1_count(MAX2(count / 3, 1));
+    set_c2_count(MAX2(count - c1_count(), 1));
+  }
+  assert(count == c1_count() + c2_count(), "inconsistent compiler thread count");
 }
 
 void SimpleThresholdPolicy::set_carry_if_necessary(InvocationCounter *counter) {
--- a/hotspot/src/share/vm/runtime/thread.cpp	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/src/share/vm/runtime/thread.cpp	Mon Aug 29 08:53:32 2016 -0700
@@ -374,11 +374,14 @@
   delete handle_area();
   delete metadata_handles();
 
+  // SR_handler uses this as a termination indicator -
+  // needs to happen before os::free_thread()
+  delete _SR_lock;
+  _SR_lock = NULL;
+
   // osthread() can be NULL, if creation of thread failed.
   if (osthread() != NULL) os::free_thread(osthread());
 
-  delete _SR_lock;
-
   // clear Thread::current if thread is deleting itself.
   // Needed to ensure JNI correctly detects non-attached threads.
   if (this == Thread::current()) {
--- a/hotspot/src/share/vm/runtime/vmStructs.cpp	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/src/share/vm/runtime/vmStructs.cpp	Mon Aug 29 08:53:32 2016 -0700
@@ -2643,7 +2643,7 @@
   /* DEFAULT_CACHE_LINE_SIZE (globalDefinitions.hpp) */                   \
   /***************************************************/                   \
                                                                           \
-  declare_constant(DEFAULT_CACHE_LINE_SIZE)                               \
+  declare_preprocessor_constant("DEFAULT_CACHE_LINE_SIZE", DEFAULT_CACHE_LINE_SIZE) \
                                                                           \
   declare_constant(Deoptimization::Unpack_deopt)                          \
   declare_constant(Deoptimization::Unpack_exception)                      \
--- a/hotspot/src/share/vm/utilities/nativeCallStack.cpp	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/src/share/vm/utilities/nativeCallStack.cpp	Mon Aug 29 08:53:32 2016 -0700
@@ -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
@@ -33,6 +33,19 @@
   _hash_value(0) {
 
   if (fillStack) {
+    // We need to skip the NativeCallStack::NativeCallStack frame if a tail call is NOT used
+    // to call os::get_native_stack. A tail call is used if _NMT_NOINLINE_ is not defined
+    // (which means this is not a slowdebug build), and we are on 64-bit (except Windows).
+    // This is not necessarily a rule, but what has been obvserved to date.
+#define TAIL_CALL (!defined(_NMT_NOINLINE_) && !defined(WINDOWS) && defined(_LP64))
+#if !TAIL_CALL
+    toSkip++;
+#if (defined(_NMT_NOINLINE_) && defined(BSD) && defined(_LP64))
+    // Mac OS X slowdebug builds have this odd behavior where NativeCallStack::NativeCallStack
+    // appears as two frames, so we need to skip an extra frame.
+    toSkip++;
+#endif
+#endif
     os::get_native_stack(_stack, NMT_TrackingStackDepth, toSkip);
   } else {
     for (int index = 0; index < NMT_TrackingStackDepth; index ++) {
--- a/hotspot/test/Makefile	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/test/Makefile	Mon Aug 29 08:53:32 2016 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 1995, 2015, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 1995, 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
@@ -226,6 +226,9 @@
 ( \
   jtregExitCode=$$? && \
   _summary="$(SUMMARY_TXT)"; \
+  if [ $${jtregExitCode} = 1 ] ; then \
+    jtregExitCode=0; \
+  fi; \
   $(RM) -f $(STATS_TXT) $(RUNLIST) $(PASSLIST) $(FAILLIST) $(EXITCODE); \
   $(ECHO) "$${jtregExitCode}" > $(EXITCODE); \
   if [ -r "$${_summary}" ] ; then \
--- a/hotspot/test/TEST.groups	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/test/TEST.groups	Mon Aug 29 08:53:32 2016 -0700
@@ -167,7 +167,7 @@
   gc/survivorAlignment \
   runtime/InternalApi/ThreadCpuTimesDeadlock.java \
   runtime/NMT/JcmdSummaryDiff.java \
-  runtime/RedefineTests/RedefineAnnotations.java
+  runtime/RedefineTests/RedefineAnnotations.java \
   serviceability/sa/jmap-hashcode/Test8028623.java \
   serviceability/threads/TestFalseDeadLock.java \
   compiler/codecache/jmx \
@@ -282,7 +282,7 @@
   -compiler/c2/Test6905845.java \
   -compiler/c2/cr6340864 \
   -compiler/c2/cr6589834 \
-  -compiler/c2/cr8004867
+  -compiler/c2/cr8004867 \
   -compiler/c2/stemmer \
   -compiler/c2/Test6792161.java \
   -compiler/c2/Test6603011.java \
--- a/hotspot/test/compiler/arguments/CheckCICompilerCount.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/test/compiler/arguments/CheckCICompilerCount.java	Mon Aug 29 08:53:32 2016 -0700
@@ -23,8 +23,7 @@
 
 /*
  * @test CheckCheckCICompilerCount
- * @bug 8130858
- * @bug 8132525
+ * @bug 8130858 8132525 8162881
  * @summary Check that correct range of values for CICompilerCount are allowed depending on whether tiered is enabled or not
  * @library /testlibrary /
  * @modules java.base/jdk.internal.misc
@@ -54,6 +53,13 @@
             "-version"
         },
         {
+            "-server",
+            "-XX:+PrintFlagsFinal",
+            "-XX:CICompilerCount=1",
+            "-XX:-TieredCompilation",
+            "-version"
+        },
+        {
             "-client",
             "-XX:-TieredCompilation",
             "-XX:+PrintFlagsFinal",
@@ -66,30 +72,31 @@
             "-XX:+PrintFlagsFinal",
             "-XX:CICompilerCount=1",
             "-version"
+        },
+        {
+            "-client",
+            "-XX:+PrintFlagsFinal",
+            "-XX:CICompilerCount=1",
+            "-XX:-TieredCompilation",
+            "-version"
         }
     };
 
-    private static final String[][] NON_TIERED_EXPECTED_OUTPUTS = {
-        {
+    private static final String[] NON_TIERED_EXPECTED_OUTPUTS = {
             "CICompilerCount (0) must be at least 1",
-            "Improperly specified VM option 'CICompilerCount=0'"
-        },
-        {
+            "intx CICompilerCount                          = 1                                        {product} {command line}",
+            "intx CICompilerCount                          = 1                                        {product} {command line}",
+            "CICompilerCount (0) must be at least 1",
+            "intx CICompilerCount                          = 1                                        {product} {command line}",
             "intx CICompilerCount                          = 1                                        {product} {command line}"
-        },
-        {
-            "CICompilerCount (0) must be at least 1",
-            "Improperly specified VM option 'CICompilerCount=0'"
-        },
-        {
-            "intx CICompilerCount                          = 1                                        {product} {command line}"
-        }
     };
 
     private static final int[] NON_TIERED_EXIT = {
         1,
         0,
+        0,
         1,
+        0,
         0
     };
 
@@ -104,6 +111,22 @@
         {
             "-server",
             "-XX:+TieredCompilation",
+            "-XX:TieredStopAtLevel=1",
+            "-XX:+PrintFlagsFinal",
+            "-XX:CICompilerCount=1",
+            "-version"
+        },
+        {
+            "-server",
+            "-XX:+TieredCompilation",
+            "-XX:+PrintFlagsFinal",
+            "-XX:CICompilerCount=1",
+            "-XX:TieredStopAtLevel=1",
+            "-version"
+        },
+        {
+            "-server",
+            "-XX:+TieredCompilation",
             "-XX:+PrintFlagsFinal",
             "-XX:CICompilerCount=2",
             "-version"
@@ -118,37 +141,51 @@
         {
             "-client",
             "-XX:+TieredCompilation",
+            "-XX:TieredStopAtLevel=1",
+            "-XX:+PrintFlagsFinal",
+            "-XX:CICompilerCount=1",
+            "-version"
+        },
+        {
+            "-client",
+            "-XX:+TieredCompilation",
+            "-XX:+PrintFlagsFinal",
+            "-XX:CICompilerCount=1",
+            "-XX:TieredStopAtLevel=1",
+            "-version"
+        },
+        {
+            "-client",
+            "-XX:+TieredCompilation",
             "-XX:+PrintFlagsFinal",
             "-XX:CICompilerCount=2",
             "-version"
         }
     };
 
-    private static final String[][] TIERED_EXPECTED_OUTPUTS = {
-        {
+    private static final String[] TIERED_EXPECTED_OUTPUTS = {
             "CICompilerCount (1) must be at least 2",
-            "Improperly specified VM option 'CICompilerCount=1'"
-        },
-        {
-            "intx CICompilerCount                          = 2                                        {product} {command line, ergonomic}"
-        },
-        {
+            "intx CICompilerCount                          = 1                                        {product} {command line}",
+            "intx CICompilerCount                          = 1                                        {product} {command line}",
+            "intx CICompilerCount                          = 2                                        {product} {command line}",
             "CICompilerCount (1) must be at least 2",
-            "Improperly specified VM option 'CICompilerCount=1'"
-        },
-        {
-            "intx CICompilerCount                          = 2                                        {product} {command line, ergonomic}"
-        }
+            "intx CICompilerCount                          = 1                                        {product} {command line}",
+            "intx CICompilerCount                          = 1                                        {product} {command line}",
+            "intx CICompilerCount                          = 2                                        {product} {command line}",
     };
 
     private static final int[] TIERED_EXIT = {
         1,
         0,
+        0,
+        0,
         1,
+        0,
+        0,
         0
     };
 
-    private static void verifyValidOption(String[] arguments, String[] expected_outputs, int exit, boolean tiered) throws Exception {
+    private static void verifyValidOption(String[] arguments, String expected_output, int exit, boolean tiered) throws Exception {
         ProcessBuilder pb;
         OutputAnalyzer out;
 
@@ -157,9 +194,7 @@
 
         try {
             out.shouldHaveExitValue(exit);
-            for (String expected_output : expected_outputs) {
-                out.shouldContain(expected_output);
-            }
+            out.shouldContain(expected_output);
         } catch (RuntimeException e) {
             // Check if tiered compilation is available in this JVM
             // Version. Throw exception only if it is available.
--- a/hotspot/test/compiler/arraycopy/TestEliminatedArrayCopyDeopt.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/test/compiler/arraycopy/TestEliminatedArrayCopyDeopt.java	Mon Aug 29 08:53:32 2016 -0700
@@ -25,7 +25,6 @@
  * @test
  * @bug 8130847 8156760
  * @summary Eliminated instance/array written to by an array copy variant must be correctly initialized when reallocated at a deopt
- * @ignore 8136818
  * @run main/othervm -XX:-BackgroundCompilation -XX:-UseOnStackReplacement
  *                   compiler.arraycopy.TestEliminatedArrayCopyDeopt
  * @run main/othervm -XX:-BackgroundCompilation -XX:-UseOnStackReplacement
--- a/hotspot/test/compiler/c2/Test6792161.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/test/compiler/c2/Test6792161.java	Mon Aug 29 08:53:32 2016 -0700
@@ -27,7 +27,7 @@
  * @bug 6792161
  * @summary assert("No dead instructions after post-alloc")
  *
- * @run main/othervm/timeout=600 -Xcomp -XX:MaxInlineSize=120 compiler.c2.Test6792161
+ * @run main/othervm/timeout=600 -Xcomp -XX:-TieredCompilation -XX:MaxInlineSize=120 compiler.c2.Test6792161
  */
 
 package compiler.c2;
--- a/hotspot/test/compiler/codecache/jmx/InitialAndMaxUsageTest.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/test/compiler/codecache/jmx/InitialAndMaxUsageTest.java	Mon Aug 29 08:53:32 2016 -0700
@@ -36,6 +36,11 @@
  *     -XX:CompileCommand=compileonly,null::* -XX:-UseLargePages
  *     -XX:+SegmentedCodeCache
  *     compiler.codecache.jmx.InitialAndMaxUsageTest
+ * @run main/othervm -Xbootclasspath/a:. -XX:-UseCodeCacheFlushing
+ *     -XX:-MethodFlushing -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI
+ *     -XX:CompileCommand=compileonly,null::* -XX:-UseLargePages
+ *     -XX:-SegmentedCodeCache
+ *     compiler.codecache.jmx.InitialAndMaxUsageTest
  */
 
 package compiler.codecache.jmx;
@@ -70,10 +75,16 @@
         }
     }
 
-    private void fillWithSize(long size, List<Long> blobs) {
+    private void fillWithSize(long size, List<Long> blobs, MemoryPoolMXBean bean) {
         long blob;
-        while ((blob = CodeCacheUtils.WB.allocateCodeBlob(size, btype.id))
-                != 0L) {
+        /* Don't fill too much to have space for adapters. So, stop after crossing 95% and
+           don't allocate in case we'll cross 97% on next allocation. We can hit situation
+           like 94% -> (1 allocation) -> 100% otherwise. So, check if
+           <Usage + allocatedSize> is less than 97%, then allocate in case it is, then, stop
+           further allocations with given size in case <Usage> more than 95% */
+        while (((double) bean.getUsage().getUsed() + size <= (CACHE_USAGE_COEF + 0.02d)  * maxSize)
+                && (blob = CodeCacheUtils.WB.allocateCodeBlob(size, btype.id)) != 0L
+                && ((double) bean.getUsage().getUsed() <= CACHE_USAGE_COEF * maxSize)) {
             blobs.add(blob);
         }
     }
@@ -90,13 +101,13 @@
             Asserts.assertEQ(initialUsage, 0L, "Unexpected initial usage");
         }
         ArrayList<Long> blobs = new ArrayList<>();
-        long minAllocationUnit = Math.max(0, CodeCacheUtils.MIN_ALLOCATION - headerSize);
+        long minAllocationUnit = Math.max(1, CodeCacheUtils.MIN_ALLOCATION - headerSize);
         /* now filling code cache with large-sized allocation first, since
          lots of small allocations takes too much time, so, just a small
          optimization */
         try {
             for (int coef = 1000000; coef > 0; coef /= 10) {
-                fillWithSize(coef * minAllocationUnit, blobs);
+                fillWithSize(coef * minAllocationUnit, blobs, bean);
             }
             Asserts.assertGT((double) bean.getUsage().getUsed(),
                     CACHE_USAGE_COEF * maxSize, String.format("Unable to fill "
--- a/hotspot/test/compiler/codecache/jmx/ThresholdNotificationsTest.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/test/compiler/codecache/jmx/ThresholdNotificationsTest.java	Mon Aug 29 08:53:32 2016 -0700
@@ -31,11 +31,11 @@
  * @build compiler.codecache.jmx.ThresholdNotificationsTest
  * @run driver ClassFileInstaller sun.hotspot.WhiteBox
  *                                sun.hotspot.WhiteBox$WhiteBoxPermission
- * @run main/othervm -Xbootclasspath/a:. -XX:-UseCodeCacheFlushing
+ * @run main/othervm -XX:+UnlockDiagnosticVMOptions -Xbootclasspath/a:. -XX:-UseCodeCacheFlushing
  *     -XX:+WhiteBoxAPI -XX:-MethodFlushing -XX:CompileCommand=compileonly,null::*
  *     -XX:+SegmentedCodeCache
  *     compiler.codecache.jmx.ThresholdNotificationsTest
- * @run main/othervm -Xbootclasspath/a:. -XX:-UseCodeCacheFlushing
+ * @run main/othervm -XX:+UnlockDiagnosticVMOptions -Xbootclasspath/a:. -XX:-UseCodeCacheFlushing
  *     -XX:+WhiteBoxAPI -XX:-MethodFlushing -XX:CompileCommand=compileonly,null::*
  *     -XX:-SegmentedCodeCache
  *     compiler.codecache.jmx.ThresholdNotificationsTest
@@ -63,7 +63,9 @@
 
     public static void main(String[] args) {
         for (BlobType bt : BlobType.getAvailable()) {
-            new ThresholdNotificationsTest(bt).runTest();
+            if (CodeCacheUtils.isCodeHeapPredictable(bt)) {
+                new ThresholdNotificationsTest(bt).runTest();
+            }
         }
     }
 
--- a/hotspot/test/compiler/codecache/jmx/UsageThresholdExceededTest.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/test/compiler/codecache/jmx/UsageThresholdExceededTest.java	Mon Aug 29 08:53:32 2016 -0700
@@ -63,7 +63,9 @@
     public static void main(String[] args) {
         int iterationsCount = Integer.getInteger("jdk.test.lib.iterations", 1);
         for (BlobType btype : BlobType.getAvailable()) {
-            new UsageThresholdExceededTest(btype, iterationsCount).runTest();
+            if (CodeCacheUtils.isCodeHeapPredictable(btype)) {
+                new UsageThresholdExceededTest(btype, iterationsCount).runTest();
+            }
         }
     }
 
--- a/hotspot/test/compiler/codecache/jmx/UsageThresholdIncreasedTest.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/test/compiler/codecache/jmx/UsageThresholdIncreasedTest.java	Mon Aug 29 08:53:32 2016 -0700
@@ -29,9 +29,9 @@
  * @modules java.base/jdk.internal.misc
  *          java.management
  *
+ * @build compiler.codecache.jmx.UsageThresholdIncreasedTest
  * @run driver ClassFileInstaller sun.hotspot.WhiteBox
  *                                sun.hotspot.WhiteBox$WhiteBoxPermission
- * @build compiler.codecache.jmx.UsageThresholdIncreasedTest
  * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions
  *     -XX:+WhiteBoxAPI -XX:-UseCodeCacheFlushing  -XX:-MethodFlushing
  *     -XX:CompileCommand=compileonly,null::*
--- a/hotspot/test/compiler/codecache/stress/RandomAllocationTest.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/test/compiler/codecache/stress/RandomAllocationTest.java	Mon Aug 29 08:53:32 2016 -0700
@@ -24,6 +24,7 @@
 
 /*
  * @test RandomAllocationTest
+ * @key stress
  * @summary stressing code cache by allocating randomly sized "dummy" code blobs
  * @library /testlibrary /test/lib /
  * @modules java.base/jdk.internal.misc
--- a/hotspot/test/compiler/codecache/stress/UnexpectedDeoptimizationTest.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/test/compiler/codecache/stress/UnexpectedDeoptimizationTest.java	Mon Aug 29 08:53:32 2016 -0700
@@ -24,6 +24,7 @@
 
 /*
  * @test UnexpectedDeoptimizationTest
+ * @key stress
  * @summary stressing code cache by forcing unexpected deoptimizations
  * @library /testlibrary /test/lib /
  * @modules java.base/jdk.internal.misc
--- a/hotspot/test/compiler/codegen/aes/TestAESMain.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/test/compiler/codegen/aes/TestAESMain.java	Mon Aug 29 08:53:32 2016 -0700
@@ -25,6 +25,7 @@
 /**
  * @test
  * @bug 7184394
+ * @key stress
  * @summary add intrinsics to use AES instructions
  * @library /testlibrary /
  * @modules java.base/jdk.internal.misc
--- a/hotspot/test/compiler/floatingpoint/ModNaN.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/test/compiler/floatingpoint/ModNaN.java	Mon Aug 29 08:53:32 2016 -0700
@@ -26,7 +26,6 @@
  * @bug 8015396
  * @summary double a%b returns NaN for some (a,b) (|a| < inf, |b|>0) (on Core i7 980X)
  *
- * @ignore 8145543
  * @run main compiler.floatingpoint.ModNaN
  */
 
--- a/hotspot/test/compiler/intrinsics/IntrinsicAvailableTest.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/test/compiler/intrinsics/IntrinsicAvailableTest.java	Mon Aug 29 08:53:32 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+ * 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
@@ -114,7 +114,7 @@
 
     public void test() throws Exception {
         Executable intrinsicMethod = testCase.getExecutable();
-        if (Platform.isServer()) {
+        if (Platform.isServer() && (TIERED_STOP_AT_LEVEL == COMP_LEVEL_FULL_OPTIMIZATION)) {
             if (TIERED_COMPILATION) {
                 checkIntrinsicForCompilationLevel(intrinsicMethod, COMP_LEVEL_SIMPLE);
             }
--- a/hotspot/test/compiler/intrinsics/IntrinsicDisabledTest.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/test/compiler/intrinsics/IntrinsicDisabledTest.java	Mon Aug 29 08:53:32 2016 -0700
@@ -59,9 +59,9 @@
     private static final int COMP_LEVEL_FULL_OPTIMIZATION = 4;
 
     /* Determine if tiered compilation is enabled. */
-    private static boolean isTieredCompilationEnabled() {
-        return Boolean.valueOf(Objects.toString(wb.getVMFlag("TieredCompilation")));
-    }
+    private static final boolean TIERED_COMPILATION = wb.getBooleanVMFlag("TieredCompilation");
+
+    private static final int TIERED_STOP_AT_LEVEL = wb.getIntxVMFlag("TieredStopAtLevel").intValue();
 
     /* This test uses several methods from jdk.internal.misc.Unsafe. The method
      * getMethod() returns a different Executable for each different
@@ -202,8 +202,8 @@
     }
 
     public static void main(String args[]) {
-        if (Platform.isServer()) {
-            if (isTieredCompilationEnabled()) {
+        if (Platform.isServer() && (TIERED_STOP_AT_LEVEL == COMP_LEVEL_FULL_OPTIMIZATION)) {
+            if (TIERED_COMPILATION) {
                 test(COMP_LEVEL_SIMPLE);
             }
             test(COMP_LEVEL_FULL_OPTIMIZATION);
--- a/hotspot/test/compiler/jvmci/common/patches/jdk.vm.ci/jdk/vm/ci/hotspot/CompilerToVMHelper.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/test/compiler/jvmci/common/patches/jdk.vm.ci/jdk/vm/ci/hotspot/CompilerToVMHelper.java	Mon Aug 29 08:53:32 2016 -0700
@@ -273,8 +273,8 @@
         return CTVM.getResolvedJavaMethod(base, displacement);
     }
 
-    public static HotSpotConstantPool getConstantPool(Object base, long displacement) {
-        return CTVM.getConstantPool(base, displacement);
+    public static HotSpotConstantPool getConstantPool(Object object) {
+        return CTVM.getConstantPool(object);
     }
 
     public static HotSpotResolvedObjectType getResolvedJavaType(Object base,
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/compiler/jvmci/common/testcases/DuplicateSimpleSingleImplementerInterface.java	Mon Aug 29 08:53:32 2016 -0700
@@ -0,0 +1,28 @@
+/*
+ * 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.
+ */
+
+package compiler.jvmci.common.testcases;
+
+public interface DuplicateSimpleSingleImplementerInterface {
+    void interfaceMethod();
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/compiler/jvmci/common/testcases/MultipleSuperImplementers.java	Mon Aug 29 08:53:32 2016 -0700
@@ -0,0 +1,29 @@
+/*
+ * 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.
+ */
+
+package compiler.jvmci.common.testcases;
+
+public abstract class MultipleSuperImplementers implements DuplicateSimpleSingleImplementerInterface, SimpleSingleImplementerInterface {
+    public void finalize() {
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/compiler/jvmci/common/testcases/SimpleSingleImplementerInterface.java	Mon Aug 29 08:53:32 2016 -0700
@@ -0,0 +1,28 @@
+/*
+ * 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.
+ */
+
+package compiler.jvmci.common.testcases;
+
+public interface SimpleSingleImplementerInterface {
+    void interfaceMethod();
+}
--- a/hotspot/test/compiler/jvmci/compilerToVM/FindUniqueConcreteMethodTest.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/test/compiler/jvmci/compilerToVM/FindUniqueConcreteMethodTest.java	Mon Aug 29 08:53:32 2016 -0700
@@ -32,6 +32,8 @@
  *          java.base/jdk.internal.org.objectweb.asm.tree
  *          jdk.vm.ci/jdk.vm.ci.hotspot
  *          jdk.vm.ci/jdk.vm.ci.code
+ *          jdk.vm.ci/jdk.vm.ci.meta
+ *          jdk.vm.ci/jdk.vm.ci.runtime
  * @build jdk.vm.ci/jdk.vm.ci.hotspot.CompilerToVMHelper
  * @build compiler.jvmci.compilerToVM.FindUniqueConcreteMethodTest
  * @run main/othervm -XX:+UnlockExperimentalVMOptions -XX:+EnableJVMCI
@@ -41,7 +43,10 @@
 package compiler.jvmci.compilerToVM;
 
 import compiler.jvmci.common.CTVMUtilities;
+import compiler.jvmci.common.testcases.DuplicateSimpleSingleImplementerInterface;
+import compiler.jvmci.common.testcases.SimpleSingleImplementerInterface;
 import compiler.jvmci.common.testcases.MultipleImplementer1;
+import compiler.jvmci.common.testcases.MultipleSuperImplementers;
 import compiler.jvmci.common.testcases.SingleImplementer;
 import compiler.jvmci.common.testcases.SingleImplementerInterface;
 import compiler.jvmci.common.testcases.SingleSubclass;
@@ -96,6 +101,11 @@
         // static method
         result.add(new TestCase(false, SingleSubclass.class,
                 SingleSubclass.class, "staticMethod"));
+        // interface method
+        result.add(new TestCase(false, MultipleSuperImplementers.class,
+                                DuplicateSimpleSingleImplementerInterface.class, "interfaceMethod", false));
+        result.add(new TestCase(false, MultipleSuperImplementers.class,
+                                SimpleSingleImplementerInterface.class, "interfaceMethod", false));
         return result;
     }
 
@@ -103,7 +113,7 @@
         System.out.println(tcase);
         Method method = tcase.holder.getDeclaredMethod(tcase.methodName);
         HotSpotResolvedJavaMethod testMethod = CTVMUtilities
-                .getResolvedMethod(tcase.receiver, method);
+            .getResolvedMethod(tcase.methodFromReceiver ? tcase.receiver : tcase.holder, method);
         HotSpotResolvedObjectType resolvedType = CompilerToVMHelper
                 .lookupType(Utils.toJVMTypeSignature(tcase.receiver), getClass(),
                 /* resolve = */ true);
@@ -118,20 +128,25 @@
         public final Class<?> holder;
         public final String methodName;
         public final boolean isPositive;
+        public final boolean methodFromReceiver;
 
         public TestCase(boolean isPositive, Class<?> clazz, Class<?> holder,
-                String methodName) {
+                        String methodName, boolean methodFromReceiver) {
             this.receiver = clazz;
             this.methodName = methodName;
             this.isPositive = isPositive;
             this.holder = holder;
+            this.methodFromReceiver = methodFromReceiver;
+        }
+
+        public TestCase(boolean isPositive, Class<?> clazz, Class<?> holder, String methodName) {
+            this(isPositive, clazz, holder, methodName, true);
         }
 
         @Override
         public String toString() {
-            return String.format("CASE: receiver=%s, holder=%s, method=%s,"
-                    + " isPositive=%s", receiver.getName(),
-                    holder.getName(), methodName, isPositive);
+            return String.format("CASE: receiver=%s, holder=%s, method=%s, isPositive=%s, methodFromReceiver=%s",
+                                 receiver.getName(), holder.getName(), methodName, isPositive, methodFromReceiver);
         }
     }
 }
--- a/hotspot/test/compiler/jvmci/compilerToVM/GetConstantPoolTest.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/test/compiler/jvmci/compilerToVM/GetConstantPoolTest.java	Mon Aug 29 08:53:32 2016 -0700
@@ -29,187 +29,76 @@
  * @library /testlibrary /test/lib /
  * @library ../common/patches
  * @modules java.base/jdk.internal.misc
- * @modules jdk.vm.ci/jdk.vm.ci.hotspot
+ * @modules java.base/jdk.internal.org.objectweb.asm
+            java.base/jdk.internal.org.objectweb.asm.tree
+            jdk.vm.ci/jdk.vm.ci.hotspot
  *          jdk.vm.ci/jdk.vm.ci.meta
+ *          jdk.vm.ci/jdk.vm.ci.code
  *
  * @build jdk.vm.ci/jdk.vm.ci.hotspot.CompilerToVMHelper
- * @build jdk.vm.ci/jdk.vm.ci.hotspot.PublicMetaspaceWrapperObject
  * @build compiler.jvmci.compilerToVM.GetConstantPoolTest
- * @build sun.hotspot.WhiteBox
- * @run driver ClassFileInstaller sun.hotspot.WhiteBox
- *                                sun.hotspot.WhiteBox$WhiteBoxPermission
  * @run main/othervm -Xbootclasspath/a:.
- *                   -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI
+ *                   -XX:+UnlockDiagnosticVMOptions
  *                   -XX:+UnlockExperimentalVMOptions -XX:+EnableJVMCI
  *                   compiler.jvmci.compilerToVM.GetConstantPoolTest
  */
 package compiler.jvmci.compilerToVM;
 
-import jdk.internal.misc.Unsafe;
 import jdk.test.lib.Utils;
+import compiler.jvmci.common.CTVMUtilities;
+import compiler.jvmci.common.testcases.TestCase;
 import jdk.vm.ci.hotspot.CompilerToVMHelper;
 import jdk.vm.ci.hotspot.HotSpotResolvedJavaMethod;
-import jdk.vm.ci.hotspot.PublicMetaspaceWrapperObject;
+import jdk.vm.ci.hotspot.HotSpotResolvedObjectType;
 import jdk.vm.ci.meta.ConstantPool;
-import sun.hotspot.WhiteBox;
 
 import java.lang.reflect.Field;
+import java.lang.reflect.Executable;
 
 /**
  * Tests for jdk.vm.ci.hotspot.CompilerToVM::getConstantPool method
  */
 public class GetConstantPoolTest {
-    private static enum TestCase {
-        NULL_BASE {
-            @Override
-            ConstantPool getConstantPool() {
-                return CompilerToVMHelper.getConstantPool(null,
-                        getPtrToCpAddress());
-            }
-        },
-        JAVA_METHOD_BASE {
-            @Override
-            ConstantPool getConstantPool() {
-                HotSpotResolvedJavaMethod methodInstance
-                        = CompilerToVMHelper.getResolvedJavaMethodAtSlot(
-                                TEST_CLASS, 0);
-                Field field;
-                try {
-                    // jdk.vm.ci.hotspot.HotSpotResolvedJavaMethodImpl.metaspaceMethod
-                    field = methodInstance.getClass()
-                            .getDeclaredField("metaspaceMethod");
-                    field.setAccessible(true);
-                    field.set(methodInstance, getPtrToCpAddress());
-                } catch (ReflectiveOperationException e) {
-                    throw new Error("TESTBUG : " + e, e);
-                }
 
-                return CompilerToVMHelper.getConstantPool(methodInstance, 0L);
-            }
-        },
-        CONSTANT_POOL_BASE {
-            @Override
-            ConstantPool getConstantPool() {
-                ConstantPool cpInst;
-                try {
-                    cpInst = CompilerToVMHelper.getConstantPool(null,
-                            getPtrToCpAddress());
-                    Field field = CompilerToVMHelper.HotSpotConstantPoolClass()
-                            .getDeclaredField("metaspaceConstantPool");
-                    field.setAccessible(true);
-                    field.set(cpInst, getPtrToCpAddress());
-                } catch (ReflectiveOperationException e) {
-                    throw new Error("TESTBUG : " + e.getMessage(), e);
-                }
-                return CompilerToVMHelper.getConstantPool(cpInst, 0L);
-            }
-        },
-        CONSTANT_POOL_BASE_IN_TWO {
-            @Override
-            ConstantPool getConstantPool() {
-                long ptr = getPtrToCpAddress();
-                ConstantPool cpInst;
-                try {
-                    cpInst = CompilerToVMHelper.getConstantPool(null, ptr);
-                    Field field = CompilerToVMHelper.HotSpotConstantPoolClass()
-                            .getDeclaredField("metaspaceConstantPool");
-                    field.setAccessible(true);
-                    field.set(cpInst, ptr / 2L);
-                } catch (ReflectiveOperationException e) {
-                    throw new Error("TESTBUG : " + e.getMessage(), e);
-                }
-                return CompilerToVMHelper.getConstantPool(cpInst,
-                        ptr - ptr / 2L);
-            }
-        },
-        CONSTANT_POOL_BASE_ZERO {
-            @Override
-            ConstantPool getConstantPool() {
-                long ptr = getPtrToCpAddress();
-                ConstantPool cpInst;
-                try {
-                    cpInst = CompilerToVMHelper.getConstantPool(null, ptr);
-                    Field field = CompilerToVMHelper.HotSpotConstantPoolClass()
-                            .getDeclaredField("metaspaceConstantPool");
-                    field.setAccessible(true);
-                    field.set(cpInst, 0L);
-                } catch (ReflectiveOperationException e) {
-                    throw new Error("TESTBUG : " + e.getMessage(), e);
-                }
-                return CompilerToVMHelper.getConstantPool(cpInst, ptr);
-            }
-        },
-        ;
-        abstract ConstantPool getConstantPool();
+    public static void testMethod(Executable executable) {
+        test(CTVMUtilities.getResolvedMethod(executable));
     }
 
-    private static final WhiteBox WB = WhiteBox.getWhiteBox();
-    private static final Unsafe UNSAFE = Utils.getUnsafe();
+    public static void testClass(Class cls) {
+        HotSpotResolvedObjectType type = CompilerToVMHelper
+                .lookupType(Utils.toJVMTypeSignature(cls),
+                        GetConstantPoolTest.class, /* resolve = */ true);
+        test(type);
+    }
 
-    private static final Class TEST_CLASS = GetConstantPoolTest.class;
-    private static final long CP_ADDRESS
-            = WB.getConstantPool(GetConstantPoolTest.class);
-
-    public void test(TestCase testCase) {
-        System.out.println(testCase.name());
-        ConstantPool cp = testCase.getConstantPool();
-        String cpStringRep = cp.toString();
-        String cpClassSimpleName
-                = CompilerToVMHelper.HotSpotConstantPoolClass().getSimpleName();
-        if (!cpStringRep.contains(cpClassSimpleName)
-                || !cpStringRep.contains(TEST_CLASS.getName())) {
-            String msg = String.format("%s : "
-                    + " Constant pool is not valid."
-                    + " String representation should contain \"%s\" and \"%s\"",
-                    testCase.name(), cpClassSimpleName,
-                    TEST_CLASS.getName());
-            throw new AssertionError(msg);
-        }
+    private static void test(Object object) {
+        ConstantPool cp = CompilerToVMHelper.getConstantPool(object);
+        System.out.println(object + " -> " + cp);
     }
 
     public static void main(String[] args) {
-        GetConstantPoolTest test = new GetConstantPoolTest();
-        for (TestCase testCase : TestCase.values()) {
-            test.test(testCase);
-        }
-        testObjectBase();
-        testMetaspaceWrapperBase();
+        TestCase.getAllClasses().forEach(GetConstantPoolTest::testClass);
+        TestCase.getAllExecutables().forEach(GetConstantPoolTest::testMethod);
+        testNull();
+        testObject();
     }
 
-    private static void testObjectBase() {
+    private static void testNull() {
         try {
-            Object cp = CompilerToVMHelper.getConstantPool(new Object(), 0L);
-            throw new AssertionError("Test OBJECT_BASE."
+            Object cp = CompilerToVMHelper.getConstantPool(null);
+            throw new AssertionError("Test OBJECT."
+                + " Expected IllegalArgumentException has not been caught");
+        } catch (NullPointerException npe) {
+            // expected
+        }
+    }
+    private static void testObject() {
+        try {
+            Object cp = CompilerToVMHelper.getConstantPool(new Object());
+            throw new AssertionError("Test OBJECT."
                 + " Expected IllegalArgumentException has not been caught");
         } catch (IllegalArgumentException iae) {
             // expected
         }
     }
-    private static void testMetaspaceWrapperBase() {
-        try {
-            Object cp = CompilerToVMHelper.getConstantPool(
-                    new PublicMetaspaceWrapperObject() {
-                        @Override
-                        public long getMetaspacePointer() {
-                            return getPtrToCpAddress();
-                        }
-                    }, 0L);
-            throw new AssertionError("Test METASPACE_WRAPPER_BASE."
-                + " Expected IllegalArgumentException has not been caught");
-        } catch (IllegalArgumentException iae) {
-            // expected
-        }
-    }
-
-    private static long getPtrToCpAddress() {
-        Field field;
-        try {
-            field = TEST_CLASS.getDeclaredField("CP_ADDRESS");
-        } catch (NoSuchFieldException nsfe) {
-            throw new Error("TESTBUG : cannot find field \"CP_ADDRESS\" : "
-                    + nsfe.getMessage(), nsfe);
-        }
-        Object base = UNSAFE.staticFieldBase(field);
-        return WB.getObjectAddress(base) + UNSAFE.staticFieldOffset(field);
-    }
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/compiler/runtime/cr8015436/Driver8015436.java	Mon Aug 29 08:53:32 2016 -0700
@@ -0,0 +1,43 @@
+/*
+ * 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.
+ */
+
+package compiler.runtime.cr8015436;
+
+import jdk.test.lib.process.OutputAnalyzer;
+import jdk.test.lib.process.ProcessTools;
+
+public class Driver8015436 {
+    public static void main(String args[]) {
+        OutputAnalyzer oa;
+        try {
+            oa = ProcessTools.executeProcess(ProcessTools.createJavaProcessBuilder(
+                    /* add test vm options */ true, Test8015436.class.getName()));
+        } catch (Exception ex) {
+            throw new Error("TESTBUG: exception while running child process: " + ex, ex);
+        }
+        oa.shouldHaveExitValue(0);
+        oa.shouldContain(Test8015436.SOME_MTD_INVOKED);
+        oa.shouldContain(Test8015436.DEFAULT_MTD_INVOKED_DIRECTLY);
+        oa.shouldContain(Test8015436.DEFAULT_MTD_INVOKED_MH);
+    }
+}
--- a/hotspot/test/compiler/runtime/cr8015436/Test8015436.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/test/compiler/runtime/cr8015436/Test8015436.java	Mon Aug 29 08:53:32 2016 -0700
@@ -25,8 +25,12 @@
  * @test
  * @bug 8015436
  * @summary the IK _initial_method_idnum value must be adjusted if overpass methods are added
+ * @library /test/lib/share/classes /
+ * @modules java.base/jdk.internal.misc
+ * @build compiler.runtime.cr8015436.Test8015436
+ *        compiler.runtime.cr8015436.Driver8015436
  *
- * @run main compiler.runtime.cr8015436.Test8015436
+ * @run driver compiler.runtime.cr8015436.Driver8015436
  */
 
 /*
@@ -45,20 +49,24 @@
 import java.lang.invoke.MethodType;
 
 public class Test8015436 implements InterfaceWithDefaultMethod {
+    public static final String SOME_MTD_INVOKED = "someMethod() invoked";
+    public static final String DEFAULT_MTD_INVOKED_DIRECTLY = "defaultMethod() invoked directly";
+    public static final String DEFAULT_MTD_INVOKED_MH = "defaultMethod() invoked via a MethodHandle";
+
     @Override
     public void someMethod() {
-        System.out.println("someMethod() invoked");
+        System.out.println(SOME_MTD_INVOKED);
     }
 
     public static void main(String[] args) throws Throwable {
         Test8015436 testObj = new Test8015436();
         testObj.someMethod();
-        testObj.defaultMethod("invoked directly");
+        testObj.defaultMethod(DEFAULT_MTD_INVOKED_DIRECTLY);
 
         MethodHandles.Lookup lookup = MethodHandles.lookup();
         MethodType   mt = MethodType.methodType(void.class, String.class);
         MethodHandle mh = lookup.findVirtual(Test8015436.class, "defaultMethod", mt);
-        mh.invokeExact(testObj, "invoked via a MethodHandle");
+        mh.invokeExact(testObj, DEFAULT_MTD_INVOKED_MH);
     }
 }
 
@@ -66,7 +74,7 @@
     public void someMethod();
 
     default public void defaultMethod(String str){
-        System.out.println("defaultMethod() " + str);
+        System.out.println(str);
     }
 }
 /*
--- a/hotspot/test/gc/g1/ihop/TestIHOPErgo.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/test/gc/g1/ihop/TestIHOPErgo.java	Mon Aug 29 08:53:32 2016 -0700
@@ -24,6 +24,7 @@
  /*
  * @test TestIHOPErgo
  * @bug 8148397
+ * @key stress
  * @summary Test checks that behavior of Adaptive and Static IHOP at concurrent cycle initiation
  * @requires vm.gc.G1
  * @requires !vm.flightRecorder
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/runtime/NMT/CheckForProperDetailStackTrace.java	Mon Aug 29 08:53:32 2016 -0700
@@ -0,0 +1,114 @@
+/*
+ * 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
+ * @key nmt
+ * @summary Running with NMT detail should produce expected stack traces.
+ * @library /testlibrary
+ * @modules java.base/jdk.internal.misc
+ *          java.management
+ */
+
+import jdk.test.lib.*;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+public class CheckForProperDetailStackTrace {
+    /* The stack trace we look for by default. Note that :: has been replaced by .*
+       to make sure it maches even if the symbol is not unmangled. */
+    public static String stackTraceDefault =
+        ".*ModuleEntryTable.*new_entry.*\n" +
+        ".*ModuleEntryTable.*locked_create_entry_or_null.*\n" +
+        ".*Modules.*define_module.*\n" +
+        ".*JVM_DefineModule.*\n";
+
+    /* The stack trace we look for on Solaris and Windows slowdebug builds. For some
+       reason ALWAYSINLINE for AllocateHeap is ignored, so it appears in the stack strace. */
+    public static String stackTraceAllocateHeap =
+        ".*AllocateHeap.*\n" +
+        ".*ModuleEntryTable.*new_entry.*\n" +
+        ".*ModuleEntryTable.*locked_create_entry_or_null.*\n" +
+        ".*Modules.*define_module.*\n";
+
+    /* A symbol that should always be present in NMT detail output. */
+    private static String expectedSymbol =
+        "locked_create_entry_or_null";
+
+    private static final String jdkDebug = System.getProperty("jdk.debug");
+    private static boolean isSlowDebugBuild() {
+        return (jdkDebug.toLowerCase().equals("slowdebug"));
+    }
+
+    public static void main(String args[]) throws Exception {
+        ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
+            "-XX:+UnlockDiagnosticVMOptions",
+            "-XX:NativeMemoryTracking=detail",
+            "-XX:+PrintNMTStatistics",
+            "-version");
+        OutputAnalyzer output = new OutputAnalyzer(pb.start());
+
+        output.shouldHaveExitValue(0);
+
+        // We should never see either of these frames because they are supposed to be skipped. */
+        output.shouldNotContain("NativeCallStack::NativeCallStack");
+        output.shouldNotContain("os::get_native_stack");
+
+        // AllocateHeap shouldn't be in the output because it is suppose to always be inlined.
+        // We check for that here, but allow it for Windows and Solaris slowdebug builds because
+        // the compiler ends up not inlining AllocateHeap.
+        Boolean okToHaveAllocateHeap =
+            isSlowDebugBuild() && (Platform.isSolaris() || Platform.isWindows());
+        if (!okToHaveAllocateHeap) {
+            output.shouldNotContain("AllocateHeap");
+        }
+
+        // See if we have any stack trace symbols in the output
+        boolean hasSymbols =
+            output.getStdout().contains(expectedSymbol) || output.getStderr().contains(expectedSymbol);
+        if (!hasSymbols) {
+            // It's ok for ARM not to have symbols, because it does not support NMT detail
+            // when targeting thumb2. It's also ok for Windows not to have symbols, because
+            // they are only available if the symbols file is included with the build.
+            if (Platform.isWindows() || Platform.isARM()) {
+                return; // we are done
+            }
+            output.reportDiagnosticSummary();
+            throw new RuntimeException("Expected symbol missing missing from output: " + expectedSymbol);
+        }
+
+        /* Make sure the expected NMT detail stack trace is found. */
+        String expectedStackTrace =
+            (okToHaveAllocateHeap ? stackTraceAllocateHeap : stackTraceDefault);
+        if (!stackTraceMatches(expectedStackTrace, output)) {
+            output.reportDiagnosticSummary();
+            throw new RuntimeException("Expected stack trace missing missing from output: " + expectedStackTrace);
+        }
+    }
+
+    public static boolean stackTraceMatches(String stackTrace, OutputAnalyzer output) {
+        Matcher stdoutMatcher = Pattern.compile(stackTrace, Pattern.MULTILINE).matcher(output.getStdout());
+        Matcher stderrMatcher = Pattern.compile(stackTrace, Pattern.MULTILINE).matcher(output.getStderr());
+        return (stdoutMatcher.find() || stderrMatcher.find());
+    }
+}
--- a/hotspot/test/runtime/StackGuardPages/exeinvoke.c	Wed Jul 20 15:07:48 2016 +0200
+++ b/hotspot/test/runtime/StackGuardPages/exeinvoke.c	Mon Aug 29 08:53:32 2016 -0700
@@ -242,7 +242,7 @@
       CLASS_PATH_OPT, javaclasspath);
 
   options[0].optionString = "-Xint";
-  options[1].optionString = "-Xss328k";
+  options[1].optionString = "-Xss1M";
   options[2].optionString = javaclasspathopt;
 
   vm_args.version = JNI_VERSION_1_2;
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/runtime/Unsafe/NestedUnsafe.java	Mon Aug 29 08:53:32 2016 -0700
@@ -0,0 +1,90 @@
+/*
+ * 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 Creates an anonymous class inside of an anonymous class.
+ * @library /testlibrary
+ * @modules java.base/jdk.internal.misc
+ *          java.compiler
+ *          java.management
+ * @run main NestedUnsafe
+ */
+
+import java.security.ProtectionDomain;
+import java.io.InputStream;
+import java.lang.*;
+import jdk.test.lib.*;
+import jdk.internal.misc.Unsafe;
+import static jdk.test.lib.Asserts.*;
+
+// package p;
+
+public class NestedUnsafe {
+    // The String concatenation should create the nested anonymous class.
+    static byte klassbuf[] = InMemoryJavaCompiler.compile("TestClass",
+        "public class TestClass { " +
+        "    public static void concat(String one, String two) throws Throwable { " +
+        "        System.out.println(one + two);" +
+        " } } ");
+
+    public static void main(String args[]) throws Exception {
+        Unsafe unsafe = Utils.getUnsafe();
+
+        Class klass = unsafe.defineAnonymousClass(NestedUnsafe.class, klassbuf, new Object[0]);
+        unsafe.ensureClassInitialized(klass);
+        Class[] cArgs = new Class[2];
+        cArgs[0] = String.class;
+        cArgs[1] = String.class;
+        try {
+            klass.getMethod("concat", cArgs).invoke(null, "AA", "BB");
+        } catch (Throwable ex) {
+            throw new RuntimeException("Exception: " + ex.toString());
+        }
+
+        // The anonymous class calls defineAnonymousClass creating a nested anonymous class.
+        byte klassbuf2[] = InMemoryJavaCompiler.compile("TestClass2",
+            "import jdk.internal.misc.Unsafe; " +
+            "public class TestClass2 { " +
+            "    public static void doit() throws Throwable { " +
+            "        Unsafe unsafe = jdk.internal.misc.Unsafe.getUnsafe(); " +
+            "        Class klass2 = unsafe.defineAnonymousClass(TestClass2.class, NestedUnsafe.klassbuf, new Object[0]); " +
+            "        unsafe.ensureClassInitialized(klass2); " +
+            "        Class[] dArgs = new Class[2]; " +
+            "        dArgs[0] = String.class; " +
+            "        dArgs[1] = String.class; " +
+            "        try { " +
+            "            klass2.getMethod(\"concat\", dArgs).invoke(null, \"CC\", \"DD\"); " +
+            "        } catch (Throwable ex) { " +
+            "            throw new RuntimeException(\"Exception: \" + ex.toString()); " +
+            "        } " +
+            "} } ",
+            "-XaddExports:java.base/jdk.internal.misc=ALL-UNNAMED");
+        Class klass2 = unsafe.defineAnonymousClass(NestedUnsafe.class, klassbuf2, new Object[0]);
+        try {
+            klass2.getMethod("doit").invoke(null);
+        } catch (Throwable ex) {
+            throw new RuntimeException("Exception: " + ex.toString());
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/serviceability/sa/sadebugd/SADebugDTest.java	Mon Aug 29 08:53:32 2016 -0700
@@ -0,0 +1,86 @@
+/*
+ * 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 Checks that the jshdb debugd utility sucessfully starts
+ *          and tries to attach to a running process
+ * @modules java.base/jdk.internal.misc
+ * @library /test/lib/share/classes
+ *
+ * @ignore 8163805
+ * @run main/othervm SADebugDTest
+ */
+import java.io.File;
+import java.util.concurrent.CountDownLatch;
+import java.io.InputStreamReader;
+import java.io.BufferedReader;
+import java.io.Reader;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Predicate;
+import static jdk.test.lib.Asserts.assertTrue;
+import static jdk.test.lib.Platform.shouldSAAttach;
+import static jdk.test.lib.process.ProcessTools.startProcess;
+
+public class SADebugDTest {
+
+    private static final String GOLDEN = "Attaching to process ID %d and starting RMI services, please wait...";
+
+    private static final String JAVA_HOME = (System.getProperty("test.jdk") != null)
+            ? System.getProperty("test.jdk") : System.getProperty("java.home");
+
+    private static final String JAVA_BIN_DIR
+            = JAVA_HOME + File.separator + "bin" + File.separator;
+
+    private static final String JHSDB = JAVA_BIN_DIR + "jhsdb";
+
+    public static void main(String[] args) throws Exception {
+
+        if (!shouldSAAttach()) {
+            log("Not possible to attach the SA. Skipping the test");
+            return;
+        }
+
+        long ourPid = ProcessHandle.current().getPid();
+
+        // The string we are expecting in the debugd ouput
+        String golden = String.format(GOLDEN, ourPid);
+
+        // We are going to run 'jhsdb debugd <our pid>'
+        // The startProcess will block untl the 'golden' string appears in either process' stdout or stderr
+        // In case of timeout startProcess kills the debugd process
+        ProcessBuilder pb = new ProcessBuilder();
+        pb.command(JHSDB, "debugd", String.valueOf(ourPid));
+        Process debugd = startProcess("debugd", pb, null, (line) -> line.trim().contains(golden), 0, TimeUnit.SECONDS);
+
+        // If we are here, this means we have received the golden line and the test has passed
+        // The debugd remains running, we have to kill it
+        debugd.destroy();
+
+    }
+
+    private static void log(String string) {
+        System.out.println(string);
+    }
+
+}
--- a/jaxp/.hgtags	Wed Jul 20 15:07:48 2016 +0200
+++ b/jaxp/.hgtags	Mon Aug 29 08:53:32 2016 -0700
@@ -374,3 +374,4 @@
 74241304e87b0d463391a8ecab40979b5af86dc2 jdk-9+129
 e66cdc2de6b02443911d386fc9217b0d824d0686 jdk-9+130
 874082a9b565a7092a40bfa934a6e3e3c3455a60 jdk-9+131
+907445d85e680ea410fe2c83c0ec64b5508e4f3e jdk-9+132
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/res/XSLTErrorResources.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/res/XSLTErrorResources.java	Mon Aug 29 08:53:32 2016 -0700
@@ -17,9 +17,6 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-/*
- * $Id: XSLTErrorResources.java,v 1.2.4.1 2005/09/13 09:55:37 pvedula Exp $
- */
 package com.sun.org.apache.xalan.internal.res;
 
 import java.util.ListResourceBundle;
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/compiler/util/ErrorMessages.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/compiler/util/ErrorMessages.java	Mon Aug 29 08:53:32 2016 -0700
@@ -17,9 +17,6 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-/*
- * $Id: ErrorMessages.java,v 1.2.4.1 2005/09/15 09:59:41 pvedula Exp $
- */
 
 package com.sun.org.apache.xalan.internal.xsltc.compiler.util;
 
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/runtime/ErrorMessages.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/runtime/ErrorMessages.java	Mon Aug 29 08:53:32 2016 -0700
@@ -17,9 +17,6 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-/*
- * $Id: ErrorMessages.java,v 1.2.4.1 2005/09/14 05:06:42 pvedula Exp $
- */
 
 package com.sun.org.apache.xalan.internal.xsltc.runtime;
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/dom/AbortException.java	Mon Aug 29 08:53:32 2016 -0700
@@ -0,0 +1,36 @@
+/*
+ * 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 com.sun.org.apache.xerces.internal.dom;
+
+public class AbortException extends RuntimeException {
+
+        private static final long serialVersionUID = 2608302175475740417L;
+
+        /**
+         * Constructor AbortException
+         */
+        public AbortException() { super(null, null, false, false); }
+}
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/dom/DOMNormalizer.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/dom/DOMNormalizer.java	Mon Aug 29 08:53:32 2016 -0700
@@ -26,6 +26,7 @@
 import java.io.StringReader;
 import java.util.Vector;
 
+import com.sun.org.apache.xerces.internal.dom.AbortException;
 import com.sun.org.apache.xerces.internal.impl.Constants;
 import com.sun.org.apache.xerces.internal.impl.RevalidationHandler;
 import com.sun.org.apache.xerces.internal.impl.dtd.DTDGrammar;
@@ -157,11 +158,6 @@
     // attribute value normalization
     final XMLString fNormalizedValue = new XMLString(new char[16], 0, 0);
 
-    /**
-     * If the user stops the process, this exception will be thrown.
-     */
-    public static final RuntimeException abort = new RuntimeException();
-
     //DTD validator
     private XMLDTDValidator fDTDValidator;
 
@@ -242,11 +238,8 @@
                                         XMLGrammarDescription.XML_SCHEMA, fValidationHandler);
                                 fValidationHandler = null;
                         }
-                }
-                catch (RuntimeException e) {
-            if( e==abort )
-                return; // processing aborted by the user
-            throw e;    // otherwise re-throw.
+                } catch (AbortException e) {
+                    return;
                 }
 
         }
@@ -1371,10 +1364,10 @@
             error.fRelatedData = locator.fRelatedNode;
 
             if(!errorHandler.handleError(error))
-                throw abort;
+                throw new AbortException();
         }
         if( severity==DOMError.SEVERITY_FATAL_ERROR )
-            throw abort;
+            throw new AbortException();
     }
 
     protected final void updateQName (Node node, QName qname){
@@ -2043,5 +2036,4 @@
         return null;
     }
 
-
 }  // DOMNormalizer class
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/msg/DOMMessages.properties	Wed Jul 20 15:07:48 2016 +0200
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/msg/DOMMessages.properties	Mon Aug 29 08:53:32 2016 -0700
@@ -2,8 +2,6 @@
 # DOM implementation.
 #
 # The messages are arranged in key and value tuples in a ListResourceBundle.
-#
-# @version $Id: DOMMessages.properties,v 1.2 2005-08-16 22:51:51 jeffsuttor Exp $
 
         BadMessageKey = The error message corresponding to the message key can not be found.
         FormatFailed = An internal error occurred while formatting the following message:\n  
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/msg/DatatypeMessages.properties	Wed Jul 20 15:07:48 2016 +0200
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/msg/DatatypeMessages.properties	Mon Aug 29 08:53:32 2016 -0700
@@ -1,8 +1,6 @@
 # This file stores localized messages for the Xerces JAXP Datatype API implementation.
 #
 # The messages are arranged in key and value tuples in a ListResourceBundle.
-#
-# @version $Id: DatatypeMessages.properties 3021 2011-03-01 00:12:28Z joehw $
 
 BadMessageKey = The error message corresponding to the message key can not be found.
 FormatFailed = An internal error occurred while formatting the following message:\n
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/msg/JAXPValidationMessages.properties	Wed Jul 20 15:07:48 2016 +0200
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/msg/JAXPValidationMessages.properties	Mon Aug 29 08:53:32 2016 -0700
@@ -1,8 +1,6 @@
 # This file stores localized messages for the Xerces JAXP Validation API implementation.
 #
 # The messages are arranged in key and value tuples in a ListResourceBundle.
-#
-# @version $Id: JAXPValidationMessages.properties 3021 2011-03-01 00:12:28Z joehw $
 
 # Messages for message reporting
 BadMessageKey = The error message corresponding to the message key can not be found.
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/msg/SAXMessages.properties	Wed Jul 20 15:07:48 2016 +0200
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/msg/SAXMessages.properties	Mon Aug 29 08:53:32 2016 -0700
@@ -2,8 +2,6 @@
 # SAX implementation.
 #
 # The messages are arranged in key and value tuples in a ListResourceBundle.
-#
-# @version $Id: SAXMessages.properties 3021 2011-03-01 00:12:28Z joehw $
 
 
 BadMessageKey = The error message corresponding to the message key can not be found.
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/msg/XMLSchemaMessages.properties	Wed Jul 20 15:07:48 2016 +0200
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/msg/XMLSchemaMessages.properties	Mon Aug 29 08:53:32 2016 -0700
@@ -1,7 +1,5 @@
 # This file contains error and warning messages related to XML Schema
 # The messages are arranged in key and value tuples in a ListResourceBundle.
-#
-# @version $Id: XMLSchemaMessages.properties 3021 2011-03-01 00:12:28Z joehw $
 
         BadMessageKey = The error message corresponding to the message key can not be found.
         FormatFailed = An internal error occurred while formatting the following message:\n
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/msg/XMLSerializerMessages.properties	Wed Jul 20 15:07:48 2016 +0200
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/msg/XMLSerializerMessages.properties	Mon Aug 29 08:53:32 2016 -0700
@@ -4,8 +4,6 @@
 #
 # As usual with properties files, the messages are arranged in
 # key/value tuples.
-# 
-# @version $Id: XMLSerializerMessages.properties 3021 2011-03-01 00:12:28Z joehw $
 
     BadMessageKey = The error message corresponding to the message key can not be found.
     FormatFailed = An internal error occurred while formatting the following message:\n
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/msg/XPointerMessages.properties	Wed Jul 20 15:07:48 2016 +0200
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/msg/XPointerMessages.properties	Mon Aug 29 08:53:32 2016 -0700
@@ -1,8 +1,6 @@
 # This file stores localized messages for the Xerces XPointer implementation.
 #
 # The messages are arranged in key and value tuples in a ListResourceBundle.
-#
-# @version $Id: XPointerMessages.properties 3021 2011-03-01 00:12:28Z joehw $
 
 # Messages for message reporting
 BadMessageKey = The error message corresponding to the message key can not be found.
@@ -24,4 +22,4 @@
 InvalidElementSchemeXPointer = InvalidElementSchemeXPointer: The Element Scheme XPointer expression ''{0}'' is invalid.
 XPointerElementSchemeProcessingError = XPointerElementSchemeProcessingError: An error occurred while processing the XPointer element() Scheme expression.
 InvalidNCNameInElementSchemeData = InvalidNCNameInElementSchemeData: The element() Scheme contains a ShortHand Pointer ''{0}'' with an invalid NCName.
-InvalidChildSequenceCharacter = InvalidChildSequenceCharacter: The element() Scheme contains an invalid child sequence character ''{0}''. 
\ No newline at end of file
+InvalidChildSequenceCharacter = InvalidChildSequenceCharacter: The element() Scheme contains an invalid child sequence character ''{0}''. 
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/res/XMLErrorResources.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/res/XMLErrorResources.java	Mon Aug 29 08:53:32 2016 -0700
@@ -17,9 +17,6 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-/*
- * $Id: XMLErrorResources.java,v 1.2.4.1 2005/09/15 07:45:37 suresh_emailid Exp $
- */
 package com.sun.org.apache.xml.internal.res;
 
 
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/serialize/DOMSerializerImpl.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/serialize/DOMSerializerImpl.java	Mon Aug 29 08:53:32 2016 -0700
@@ -28,6 +28,7 @@
 import java.lang.reflect.Method;
 import java.util.ArrayList;
 
+import com.sun.org.apache.xerces.internal.dom.AbortException;
 import com.sun.org.apache.xerces.internal.dom.CoreDocumentImpl;
 import com.sun.org.apache.xerces.internal.dom.DOMErrorImpl;
 import com.sun.org.apache.xerces.internal.dom.DOMLocatorImpl;
@@ -501,11 +502,9 @@
         } catch (LSException lse) {
             // Rethrow LSException.
             throw lse;
+        } catch (AbortException e) {
+            return null;
         } catch (RuntimeException e) {
-            if (e == DOMNormalizer.abort) {
-                // stopped at user request
-                return null;
-            }
             throw (LSException) DOMUtil.createLSException(LSException.SERIALIZE_ERR, e).fillInStackTrace();
         } catch (IOException ioe) {
             // REVISIT: A generic IOException doesn't provide enough information
@@ -733,11 +732,9 @@
         } catch (LSException lse) {
             // Rethrow LSException.
             throw lse;
+        } catch (AbortException e) {
+            return false;
         } catch (RuntimeException e) {
-            if (e == DOMNormalizer.abort) {
-                // stopped at user request
-                return false;
-            }
             throw (LSException) DOMUtil.createLSException(LSException.SERIALIZE_ERR, e).fillInStackTrace();
         } catch (Exception e) {
             if (ser.fDOMErrorHandler != null) {
@@ -833,11 +830,9 @@
         } catch (LSException lse) {
             // Rethrow LSException.
             throw lse;
+        } catch (AbortException e) {
+            return false;
         } catch (RuntimeException e) {
-            if (e == DOMNormalizer.abort) {
-                // stopped at user request
-                return false;
-            }
             throw (LSException) DOMUtil.createLSException(LSException.SERIALIZE_ERR, e).fillInStackTrace();
         } catch (Exception e) {
             if (ser.fDOMErrorHandler != null) {
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/serializer/utils/SerializerMessages.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/serializer/utils/SerializerMessages.java	Mon Aug 29 08:53:32 2016 -0700
@@ -19,9 +19,6 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-/*
- * $Id: SerializerMessages.java,v 1.1.4.1 2005/09/08 11:03:11 suresh_emailid Exp $
- */
 package com.sun.org.apache.xml.internal.serializer.utils;
 
 import java.util.ListResourceBundle;
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xpath/internal/jaxp/XPathImplUtil.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xpath/internal/jaxp/XPathImplUtil.java	Mon Aug 29 08:53:32 2016 -0700
@@ -28,6 +28,7 @@
 import com.sun.org.apache.xalan.internal.res.XSLMessages;
 import com.sun.org.apache.xalan.internal.utils.FactoryImpl;
 import com.sun.org.apache.xml.internal.dtm.DTM;
+import com.sun.org.apache.xpath.internal.axes.LocPathIterator;
 import com.sun.org.apache.xpath.internal.objects.XObject;
 import com.sun.org.apache.xpath.internal.res.XPATHErrorResources;
 import java.io.IOException;
@@ -73,6 +74,12 @@
     XObject eval(Object contextItem, com.sun.org.apache.xpath.internal.XPath xpath)
             throws javax.xml.transform.TransformerException {
         com.sun.org.apache.xpath.internal.XPathContext xpathSupport;
+        if (contextItem == null && xpath.getExpression() instanceof LocPathIterator) {
+            // the operation must have no dependency on the context that is null
+            throw new TransformerException(XSLMessages.createXPATHMessage(
+                    XPATHErrorResources.ER_CONTEXT_CAN_NOT_BE_NULL,
+                    new Object[] {}));
+        }
         if (functionResolver != null) {
             JAXPExtensionsProvider jep = new JAXPExtensionsProvider(
                     functionResolver, featureSecureProcessing, featureManager);
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xpath/internal/res/XPATHErrorResources.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xpath/internal/res/XPATHErrorResources.java	Mon Aug 29 08:53:32 2016 -0700
@@ -17,9 +17,6 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-/*
- * $Id: XPATHErrorResources.java,v 1.2.4.1 2005/09/15 01:29:15 jeffsuttor Exp $
- */
 package com.sun.org.apache.xpath.internal.res;
 
 import java.util.ListResourceBundle;
@@ -93,6 +90,7 @@
   public static final String ER_CURRENT_TAKES_NO_ARGS =
          "ER_CURRENT_TAKES_NO_ARGS";
   public static final String ER_DOCUMENT_REPLACED = "ER_DOCUMENT_REPLACED";
+  public static final String ER_CONTEXT_CAN_NOT_BE_NULL = "ER_CONTEXT_CAN_NOT_BE_NULL";
   public static final String ER_CONTEXT_HAS_NO_OWNERDOC =
          "ER_CONTEXT_HAS_NO_OWNERDOC";
   public static final String ER_LOCALNAME_HAS_TOO_MANY_ARGS =
@@ -368,6 +366,9 @@
   { ER_DOCUMENT_REPLACED,
       "document() function implementation has been replaced by com.sun.org.apache.xalan.internal.xslt.FuncDocument!"},
 
+  { ER_CONTEXT_CAN_NOT_BE_NULL,
+      "The context can not be null when the operation is context-dependent."},
+
   { ER_CONTEXT_HAS_NO_OWNERDOC,
       "context does not have an owner document!"},
 
--- a/jaxp/src/java.xml/share/classes/javax/xml/xpath/XPath.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jaxp/src/java.xml/share/classes/javax/xml/xpath/XPath.java	Mon Aug 29 08:53:32 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 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
@@ -34,18 +34,20 @@
  *
  * <a name="XPath-evaluation"></a>
  * <table border="1" cellpadding="2">
- *   <thead>
- *     <tr>
- *       <th colspan="2">Evaluation of XPath Expressions.</th>
- *     </tr>
- *   </thead>
- *     <tr>
- *       <td>context</td>
- *       <td>
- *         If a request is made to evaluate the expression in the absence
- * of a context item, an empty document node will be used for the context.
- * For the purposes of evaluating XPath expressions, a DocumentFragment
- * is treated like a Document node.
+ *    <thead>
+ *      <tr>
+ *        <th colspan="2">Evaluation of XPath Expressions.</th>
+ *      </tr>
+ *    </thead>
+ *    <tr>
+ *      <td>context</td>
+ *      <td>
+ *        The type of the context is implementation-dependent. If the value is
+ *        null, the operation must have no dependency on the context, otherwise
+ *        an XPathExpressionException will be thrown.
+ *
+ *        For the purposes of evaluating XPath expressions, a DocumentFragment
+ *        is treated like a Document node.
  *      </td>
  *    </tr>
  *    <tr>
--- a/jaxp/src/java.xml/share/classes/javax/xml/xpath/XPathExpression.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jaxp/src/java.xml/share/classes/javax/xml/xpath/XPathExpression.java	Mon Aug 29 08:53:32 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 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
@@ -33,19 +33,20 @@
  *
  * <a name="XPathExpression-evaluation"></a>
  * <table border="1" cellpadding="2">
- *   <thead>
- *     <tr>
- *       <th colspan="2">Evaluation of XPath Expressions.</th>
- *     </tr>
- *   </thead>
- *   <tbody>
- *     <tr>
- *       <td>context</td>
- *       <td>
- *         If a request is made to evaluate the expression in the absence
- * of a context item, an empty document node will be used for the context.
- * For the purposes of evaluating XPath expressions, a DocumentFragment
- * is treated like a Document node.
+ *    <thead>
+ *      <tr>
+ *        <th colspan="2">Evaluation of XPath Expressions.</th>
+ *      </tr>
+ *    </thead>
+ *    <tr>
+ *      <td>context</td>
+ *      <td>
+ *        The type of the context is implementation-dependent. If the value is
+ *        null, the operation must have no dependency on the context, otherwise
+ *        an XPathExpressionException will be thrown.
+ *
+ *        For the purposes of evaluating XPath expressions, a DocumentFragment
+ *        is treated like a Document node.
  *      </td>
  *    </tr>
  *    <tr>
--- a/jaxp/src/java.xml/share/classes/module-info.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jaxp/src/java.xml/share/classes/module-info.java	Mon Aug 29 08:53:32 2016 -0700
@@ -23,6 +23,10 @@
  * questions.
  */
 
+/**
+ * Defines the Java API for XML Processing (JAXP), the Streaming API for XML (StAX),
+ * the Simple API for XML (SAX), and the W3C Document Object Model (DOM) API.
+ */
 module java.xml {
     exports javax.xml;
     exports javax.xml.catalog;
--- a/jaxp/test/javax/xml/jaxp/unittest/xpath/XPathTest.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jaxp/test/javax/xml/jaxp/unittest/xpath/XPathTest.java	Mon Aug 29 08:53:32 2016 -0700
@@ -24,11 +24,17 @@
 package xpath;
 
 import javax.xml.namespace.NamespaceContext;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
 import javax.xml.xpath.XPath;
+import javax.xml.xpath.XPathConstants;
+import javax.xml.xpath.XPathExpressionException;
 import javax.xml.xpath.XPathFactory;
-
+import org.testng.annotations.DataProvider;
 import org.testng.annotations.Listeners;
 import org.testng.annotations.Test;
+import org.w3c.dom.Document;
+import org.w3c.dom.Node;
 
 /*
  * @test
@@ -36,19 +42,105 @@
  * @library /javax/xml/jaxp/libs /javax/xml/jaxp/unittest
  * @run testng/othervm -DrunSecMngr=true xpath.XPathTest
  * @run testng/othervm xpath.XPathTest
- * @summary Test XPath.getNamespaceContext() is supported.
+ * @summary Test XPath functions. See details for each test.
  */
 @Listeners({jaxp.library.BasePolicy.class})
 public class XPathTest {
 
+    /*
+      @bug 6211561
+     * Verifies the specification for XPath and XPathExpression:
+     * If a null value is provided for item (the context),
+     * the expression must have no dependency on the context.
+    */
+    @Test(dataProvider = "noContextDependency")
+    public void testNoContextDependency1(String expression, Object item) throws XPathExpressionException {
+        XPath xPath = XPathFactory.newInstance().newXPath();
+        xPath.evaluate(expression, item, XPathConstants.STRING);
+    }
+
+    @Test(dataProvider = "noContextDependency")
+    public void testNoContextDependency2(String expression, Object item) throws XPathExpressionException {
+        XPath xPath = XPathFactory.newInstance().newXPath();
+        xPath.evaluateExpression(expression, item, String.class);
+    }
+
+    /*
+      @bug 6211561
+     * Verifies the specification for XPath and XPathExpression:
+     * If a null value is provided for item (the context) that the operation
+     * depends on, XPathExpressionException will be thrown
+    */
+    @Test(dataProvider = "hasContextDependency", expectedExceptions = XPathExpressionException.class)
+    public void testHasContextDependency1(String expression, Object item) throws XPathExpressionException {
+        XPath xPath = XPathFactory.newInstance().newXPath();
+        xPath.evaluate(expression, item, XPathConstants.STRING);
+    }
+
+    @Test(dataProvider = "hasContextDependency", expectedExceptions = XPathExpressionException.class)
+    public void testHasContextDependency2(String expression, Object item) throws XPathExpressionException {
+        XPath xPath = XPathFactory.newInstance().newXPath();
+        xPath.evaluateExpression(expression, item, String.class);
+    }
+
+    /*
+      @bug 6376058
+      Verifies that XPath.getNamespaceContext() is supported.
+    */
     @Test
     public void testNamespaceContext() {
-
         XPathFactory xPathFactory = XPathFactory.newInstance();
         XPath xPath = xPathFactory.newXPath();
+        NamespaceContext namespaceContext = xPath.getNamespaceContext();
+    }
 
-        NamespaceContext namespaceContext = xPath.getNamespaceContext();
+    /*
+     * DataProvider: the expression has no dependency on the context
+     */
+    @DataProvider(name = "noContextDependency")
+    public Object[][] getExpressionContext() throws Exception {
+        return new Object[][]{
+            {"1+1", (Node)null},
+            {"5 mod 2", (Node)null},
+            {"8 div 2", (Node)null},
+            {"/node", getEmptyDocument()}
+        };
+    }
 
+    /*
+     * DataProvider: the expression has dependency on the context, but the context
+     * is null.
+     */
+    @DataProvider(name = "hasContextDependency")
+    public Object[][] getExpressionContext1() throws Exception {
+        return new Object[][]{
+            {"/node", (Node)null},
+            {"//@lang", (Node)null},
+            {"bookstore//book", (Node)null},
+            {"/bookstore/book[last()]", (Node)null},
+            {"//title[@lang='en']", (Node)null},
+            {"/bookstore/book[price>9.99]", (Node)null},
+            {"/bookstore/book[price>8.99 and price<9.99]", (Node)null},
+            {"/bookstore/*", (Node)null},
+            {"//title[@*]", (Node)null},
+            {"//title | //price", (Node)null},
+            {"//book/title | //book/price", (Node)null},
+            {"/bookstore/book/title | //price", (Node)null},
+            {"child::book", (Node)null},
+            {"child::text()", (Node)null},
+            {"child::*/child::price", (Node)null}
+        };
+    }
+
+    /**
+     * Returns an empty {@link org.w3c.dom.Document}.
+     * @return a DOM Document, null in case of Exception
+     */
+    public Document getEmptyDocument() {
+        try {
+            return DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
+        } catch (ParserConfigurationException e) {
+            return null;
+        }
     }
 }
-
--- a/jaxws/.hgtags	Wed Jul 20 15:07:48 2016 +0200
+++ b/jaxws/.hgtags	Mon Aug 29 08:53:32 2016 -0700
@@ -377,3 +377,4 @@
 46a02f57218e4a8c334dbccf656fb048f823f163 jdk-9+129
 39c6293131d91aec7f2f5120395e070a937b8858 jdk-9+130
 783e7e2c587f2c7e1b9998a46d90ec196ab2a195 jdk-9+131
+9fff2477a4cadf2a9618a76f1f4fe0f20bb5ff3b jdk-9+132
--- a/jaxws/src/java.activation/share/classes/module-info.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jaxws/src/java.activation/share/classes/module-info.java	Mon Aug 29 08:53:32 2016 -0700
@@ -23,6 +23,9 @@
  * questions.
  */
 
+/**
+ * Defines the JavaBeans Activation Framework (JAF) API.
+ */
 module java.activation {
     requires public java.datatransfer;
     // dependence on java.beans.Beans to be eliminated
--- a/jaxws/src/java.annotations.common/share/classes/module-info.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jaxws/src/java.annotations.common/share/classes/module-info.java	Mon Aug 29 08:53:32 2016 -0700
@@ -23,6 +23,10 @@
  * questions.
  */
 
+/**
+ * Defines a subset of the Common Annotations API to support programs running
+ * on the Java SE Platform.
+ */
 module java.annotations.common {
     exports javax.annotation;
 }
--- a/jaxws/src/java.xml.bind/share/classes/module-info.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jaxws/src/java.xml.bind/share/classes/module-info.java	Mon Aug 29 08:53:32 2016 -0700
@@ -23,6 +23,9 @@
  * questions.
  */
 
+/**
+ * Defines the Java Architecture for XML Binding (JAXB) API.
+ */
 module java.xml.bind {
     requires public java.activation;
     requires public java.xml;
--- a/jaxws/src/java.xml.ws/share/classes/module-info.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jaxws/src/java.xml.ws/share/classes/module-info.java	Mon Aug 29 08:53:32 2016 -0700
@@ -23,6 +23,10 @@
  * questions.
  */
 
+/**
+ * Defines the Java API for XML-Based Web Services (JAX-WS), and
+ * the Web Services Metadata API.
+ */
 module java.xml.ws {
     requires public java.activation;
     requires public java.xml;
--- a/jdk/.hgtags	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/.hgtags	Mon Aug 29 08:53:32 2016 -0700
@@ -375,3 +375,4 @@
 6c827500e34587061af97ad6fef0e859280255c5 jdk-9+130
 8c57f4c293bbc5609928308a6d91ba765760b5f9 jdk-9+131
 d5c70818cd8a82e76632c8c815bdb4f75f53aeaf jdk-9+132
+3cdae27c90b5e41afe75eab904fda19fac076330 jdk-9+133
--- a/jdk/make/data/cryptopolicy/limited/default_local.policy	Wed Jul 20 15:07:48 2016 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,14 +0,0 @@
-// Some countries have import limits on crypto strength. This policy file
-// is worldwide importable.
-
-grant {
-    permission javax.crypto.CryptoPermission "DES", 64;
-    permission javax.crypto.CryptoPermission "DESede", *;
-    permission javax.crypto.CryptoPermission "RC2", 128, 
-                                     "javax.crypto.spec.RC2ParameterSpec", 128;
-    permission javax.crypto.CryptoPermission "RC4", 128;
-    permission javax.crypto.CryptoPermission "RC5", 128, 
-          "javax.crypto.spec.RC5ParameterSpec", *, 12, *;
-    permission javax.crypto.CryptoPermission "RSA", *;
-    permission javax.crypto.CryptoPermission *, 128;
-};
--- a/jdk/make/data/cryptopolicy/limited/exempt_local.policy	Wed Jul 20 15:07:48 2016 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,13 +0,0 @@
-// Some countries have import limits on crypto strength. So this file
-// will be useful.
-
-grant {
-    // There is no restriction to any algorithms if KeyRecovery is enforced.
-    permission javax.crypto.CryptoPermission *, "KeyRecovery"; 
-
-    // There is no restriction to any algorithms if KeyEscrow is enforced.
-    permission javax.crypto.CryptoPermission *, "KeyEscrow"; 
-
-    // There is no restriction to any algorithms if KeyWeakening is enforced. 
-    permission javax.crypto.CryptoPermission *, "KeyWeakening";
-};
--- a/jdk/make/data/cryptopolicy/unlimited/default_US_export.policy	Wed Jul 20 15:07:48 2016 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,5 +0,0 @@
-// Manufacturing policy file.
-grant {
-    // There is no restriction to any algorithms.
-    permission javax.crypto.CryptoAllPermission; 
-};
--- a/jdk/make/data/cryptopolicy/unlimited/default_local.policy	Wed Jul 20 15:07:48 2016 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,5 +0,0 @@
-// Country-specific policy file for countries with no limits on crypto strength.
-grant {
-    // There is no restriction to any algorithms.
-    permission javax.crypto.CryptoAllPermission; 
-};
--- a/jdk/make/gendata/Gendata-java.base.gmk	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/make/gendata/Gendata-java.base.gmk	Mon Aug 29 08:53:32 2016 -0700
@@ -34,7 +34,7 @@
 
 include GendataBlacklistedCerts.gmk
 
-include GendataPolicyJars.gmk
+include GendataCryptoPolicy.gmk
 
 ################################################################################
 
@@ -64,13 +64,19 @@
 GENDATA_JAVA_SECURITY_SRC := $(JDK_TOPDIR)/src/java.base/share/conf/security/java.security
 GENDATA_JAVA_SECURITY := $(SUPPORT_OUTPUTDIR)/modules_conf/java.base/security/java.security
 
+ifeq ($(UNLIMITED_CRYPTO), true)
+    CRYPTO.POLICY := unlimited
+else
+    CRYPTO.POLICY := limited
+endif
+
 # RESTRICTED_PKGS_SRC is optionally set in custom extension for this makefile
 
 $(GENDATA_JAVA_SECURITY): $(BUILD_TOOLS) $(GENDATA_JAVA_SECURITY_SRC) $(RESTRICTED_PKGS_SRC)
 	$(call LogInfo, Generating java.security)
 	$(call MakeDir, $(@D))
 	$(TOOL_MAKEJAVASECURITY) $(GENDATA_JAVA_SECURITY_SRC) $@ $(OPENJDK_TARGET_OS) \
-	    $(OPENJDK_TARGET_CPU_ARCH) $(RESTRICTED_PKGS_SRC)
+	    $(OPENJDK_TARGET_CPU_ARCH) $(CRYPTO.POLICY) $(RESTRICTED_PKGS_SRC)
 
 TARGETS += $(GENDATA_JAVA_SECURITY)
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/make/gendata/GendataCryptoPolicy.gmk	Mon Aug 29 08:53:32 2016 -0700
@@ -0,0 +1,72 @@
+#
+# 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
+# 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.
+#
+
+#
+# In pre-JDK9 releases, Oracle JDK has had a separately downloadable set
+# of policy files which has been a nightmare for deployment.
+#
+# We now create 2 complete initial sets of policy files and package into 
+# 2 different directories.  The crypto.policy Security property will select
+# the active policy.
+#
+# It will be up to the user/deployer to make an informed choice
+# as to whether they are legally entitled to use the unlimited policy
+# file in their environment.  The $(UNLIMITED_CRYPTO) make variable
+# determines the default directory/policy.
+#
+
+default: all
+
+include $(SPEC)
+include MakeBase.gmk
+
+
+################################################################################
+POLICY_DIR := $(SUPPORT_OUTPUTDIR)/modules_conf/java.base/security/policy
+LIMITED_POLICY_DIR := $(POLICY_DIR)/limited
+UNLIMITED_POLICY_DIR := $(POLICY_DIR)/unlimited
+
+POLICY_SRC_DIR := $(JDK_TOPDIR)/src/java.base/share/conf/security/policy
+LIMITED_POLICY_SRC_DIR := $(POLICY_SRC_DIR)/limited
+UNLIMITED_POLICY_SRC_DIR := $(POLICY_SRC_DIR)/unlimited
+
+$(POLICY_DIR)/README.txt: $(POLICY_SRC_DIR)/README.txt
+	$(install-file)
+
+$(LIMITED_POLICY_DIR)/%: $(LIMITED_POLICY_SRC_DIR)/%
+	$(install-file)
+
+$(UNLIMITED_POLICY_DIR)/%: $(UNLIMITED_POLICY_SRC_DIR)/%
+	$(install-file)
+
+TARGETS += \
+    $(POLICY_DIR)/README.txt \
+    $(LIMITED_POLICY_DIR)/default_US_export.policy \
+    $(LIMITED_POLICY_DIR)/default_local.policy \
+    $(LIMITED_POLICY_DIR)/exempt_local.policy \
+    $(UNLIMITED_POLICY_DIR)/default_US_export.policy \
+    $(UNLIMITED_POLICY_DIR)/default_local.policy \
+
+################################################################################
--- a/jdk/make/gendata/GendataPolicyJars.gmk	Wed Jul 20 15:07:48 2016 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,150 +0,0 @@
-#
-# 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
-# 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.
-#
-
-default: all
-
-include $(SPEC)
-include MakeBase.gmk
-include JarArchive.gmk
-
-
-################################################################################
-
-US_EXPORT_POLICY_JAR_DST := \
-    $(SUPPORT_OUTPUTDIR)/modules_libs/java.base/security/US_export_policy.jar
-
-US_EXPORT_POLICY_JAR_LIMITED := \
-    $(SUPPORT_OUTPUTDIR)/jce/policy/limited/US_export_policy.jar
-US_EXPORT_POLICY_JAR_UNLIMITED := \
-    $(SUPPORT_OUTPUTDIR)/jce/policy/unlimited/US_export_policy.jar
-
-#
-# TODO fix so that SetupJarArchive does not write files into SRCS
-# then we don't need this extra copying
-#
-# NOTE: We currently do not place restrictions on our limited export
-# policy. This was not a typo. This means we are shipping the same file
-# for both limited and unlimited US_export_policy.jar.  Only the local
-# policy file currently has restrictions.
-#
-US_EXPORT_POLICY_JAR_SRC_DIR := \
-    $(JDK_TOPDIR)/make/data/cryptopolicy/unlimited
-US_EXPORT_POLICY_JAR_TMP := \
-    $(SUPPORT_OUTPUTDIR)/jce/policy/unlimited/US_export_policy_jar.tmp
-
-$(US_EXPORT_POLICY_JAR_TMP)/%: $(US_EXPORT_POLICY_JAR_SRC_DIR)/%
-	$(install-file)
-
-US_EXPORT_POLICY_JAR_DEPS := \
-    $(US_EXPORT_POLICY_JAR_TMP)/default_US_export.policy
-
-$(eval $(call SetupJarArchive, BUILD_US_EXPORT_POLICY_JAR, \
-    DEPENDENCIES := $(US_EXPORT_POLICY_JAR_DEPS), \
-    SRCS := $(US_EXPORT_POLICY_JAR_TMP), \
-    SUFFIXES := .policy, \
-    JAR := $(US_EXPORT_POLICY_JAR_UNLIMITED), \
-    EXTRA_MANIFEST_ATTR := Crypto-Strength: unlimited, \
-    SKIP_METAINF := true, \
-))
-
-$(US_EXPORT_POLICY_JAR_LIMITED): \
-    $(US_EXPORT_POLICY_JAR_UNLIMITED)
-	$(call LogInfo, Copying unlimited $(patsubst $(OUTPUT_ROOT)/%,%,$@))
-	$(install-file)
-
-TARGETS += $(US_EXPORT_POLICY_JAR_LIMITED) $(US_EXPORT_POLICY_JAR_UNLIMITED)
-
-ifeq ($(UNLIMITED_CRYPTO), true)
-  $(US_EXPORT_POLICY_JAR_DST): $(US_EXPORT_POLICY_JAR_UNLIMITED)
-	$(install-file)
-else
-  $(US_EXPORT_POLICY_JAR_DST): $(US_EXPORT_POLICY_JAR_LIMITED)
-	$(install-file)
-endif
-
-POLICY_JARS += $(US_EXPORT_POLICY_JAR_DST)
-
-################################################################################
-
-LOCAL_POLICY_JAR_DST := \
-    $(SUPPORT_OUTPUTDIR)/modules_libs/java.base/security/local_policy.jar
-
-LOCAL_POLICY_JAR_LIMITED := \
-    $(SUPPORT_OUTPUTDIR)/jce/policy/limited/local_policy.jar
-LOCAL_POLICY_JAR_UNLIMITED := \
-    $(SUPPORT_OUTPUTDIR)/jce/policy/unlimited/local_policy.jar
-
-#
-# TODO fix so that SetupJarArchive does not write files into SRCS
-# then we don't need this extra copying
-#
-LOCAL_POLICY_JAR_LIMITED_TMP := \
-    $(SUPPORT_OUTPUTDIR)/jce/policy/limited/local_policy_jar.tmp
-LOCAL_POLICY_JAR_UNLIMITED_TMP := \
-    $(SUPPORT_OUTPUTDIR)/jce/policy/unlimited/local_policy_jar.tmp
-
-$(LOCAL_POLICY_JAR_LIMITED_TMP)/%: \
-    $(JDK_TOPDIR)/make/data/cryptopolicy/limited/%
-	$(install-file)
-
-$(LOCAL_POLICY_JAR_UNLIMITED_TMP)/%: \
-    $(JDK_TOPDIR)/make/data/cryptopolicy/unlimited/%
-	$(install-file)
-
-$(eval $(call SetupJarArchive, BUILD_LOCAL_POLICY_JAR_LIMITED, \
-    DEPENDENCIES := $(LOCAL_POLICY_JAR_LIMITED_TMP)/exempt_local.policy \
-        $(LOCAL_POLICY_JAR_LIMITED_TMP)/default_local.policy, \
-    SRCS := $(LOCAL_POLICY_JAR_LIMITED_TMP), \
-    SUFFIXES := .policy, \
-    JAR := $(LOCAL_POLICY_JAR_LIMITED), \
-    EXTRA_MANIFEST_ATTR := Crypto-Strength: limited, \
-    SKIP_METAINF := true, \
-))
-
-$(eval $(call SetupJarArchive, BUILD_LOCAL_POLICY_JAR_UNLIMITED, \
-    DEPENDENCIES := $(LOCAL_POLICY_JAR_UNLIMITED_TMP)/default_local.policy, \
-    SRCS := $(LOCAL_POLICY_JAR_UNLIMITED_TMP), \
-    SUFFIXES := .policy, \
-    JAR := $(LOCAL_POLICY_JAR_UNLIMITED), \
-    EXTRA_MANIFEST_ATTR := Crypto-Strength: unlimited, \
-    SKIP_METAINF := true, \
-))
-
-TARGETS += $(LOCAL_POLICY_JAR_LIMITED) $(LOCAL_POLICY_JAR_UNLIMITED)
-
-ifeq ($(UNLIMITED_CRYPTO), true)
-  $(LOCAL_POLICY_JAR_DST): $(LOCAL_POLICY_JAR_UNLIMITED)
-	$(install-file)
-else
-  $(LOCAL_POLICY_JAR_DST): $(LOCAL_POLICY_JAR_LIMITED)
-	$(install-file)
-endif
-
-POLICY_JARS += $(LOCAL_POLICY_JAR_DST)
-TARGETS += $(POLICY_JARS)
-
-################################################################################
-
-$(eval $(call IncludeCustomExtension, jdk, gendata/GendataPolicyJars.gmk))
--- a/jdk/make/launcher/Launcher-jdk.jdeps.gmk	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/make/launcher/Launcher-jdk.jdeps.gmk	Mon Aug 29 08:53:32 2016 -0700
@@ -36,3 +36,9 @@
     CFLAGS := -DEXPAND_CLASSPATH_WILDCARDS \
         -DNEVER_ACT_AS_SERVER_CLASS_MACHINE, \
 ))
+
+$(eval $(call SetupBuildLauncher, jdeprscan, \
+    MAIN_CLASS := com.sun.tools.jdeprscan.Main, \
+    CFLAGS := -DEXPAND_CLASSPATH_WILDCARDS \
+        -DNEVER_ACT_AS_SERVER_CLASS_MACHINE, \
+))
--- a/jdk/make/lib/Lib-jdk.crypto.pkcs11.gmk	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/make/lib/Lib-jdk.crypto.pkcs11.gmk	Mon Aug 29 08:53:32 2016 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2011, 2015, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2011, 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
@@ -38,8 +38,6 @@
     CFLAGS := $(CFLAGS_JDKLIB) $(addprefix -I, $(LIBJ2PKCS11_SRC)) \
         $(LIBJAVA_HEADER_FLAGS) \
         -I$(SUPPORT_OUTPUTDIR)/headers/jdk.crypto.pkcs11, \
-    DISABLED_WARNINGS_solstudio := E_DECLARATION_IN_CODE, \
-    DISABLED_WARNINGS_microsoft := 4013 4267, \
     MAPFILE := $(JDK_TOPDIR)/make/mapfiles/libj2pkcs11/mapfile-vers, \
     LDFLAGS := $(LDFLAGS_JDKLIB) \
         $(call SET_SHARED_LIBRARY_ORIGIN), \
--- a/jdk/make/src/classes/build/tools/makejavasecurity/MakeJavaSecurity.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/make/src/classes/build/tools/makejavasecurity/MakeJavaSecurity.java	Mon Aug 29 08:53:32 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, 2014, 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
@@ -35,7 +35,8 @@
  *
  * 1. Adds additional packages to the package.access and
  *    package.definition security properties.
- * 2. Filter out platform-unrelated parts
+ * 2. Filter out platform-unrelated parts.
+ * 3. Set the JCE jurisdiction policy directory.
  *
  * In order to easily maintain platform-related entries, every item
  * (including the last line) in package.access and package.definition
@@ -50,12 +51,13 @@
 
     public static void main(String[] args) throws Exception {
 
-        if (args.length < 4) {
+        if (args.length < 5) {
             System.err.println("Usage: java MakeJavaSecurity " +
                                "[input java.security file name] " +
                                "[output java.security file name] " +
                                "[openjdk target os] " +
                                "[openjdk target cpu architecture]" +
+                               "[JCE jurisdiction policy directory]" +
                                "[more restricted packages file name?]");
 
                     System.exit(1);
@@ -63,8 +65,8 @@
 
         // more restricted packages
         List<String> extraLines;
-        if (args.length == 5) {
-            extraLines = Files.readAllLines(Paths.get(args[4]));
+        if (args.length == 6) {
+            extraLines = Files.readAllLines(Paths.get(args[5]));
         } else {
             extraLines = Collections.emptyList();
         }
@@ -135,6 +137,16 @@
             }
         }
 
+        // Set the JCE policy value
+        for (int i = 0; i < lines.size(); i++) {
+            String line = lines.get(i);
+            int index = line.indexOf("crypto.policydir-tbd");
+            if (index >= 0) {
+                String prefix = line.substring(0, index);
+                lines.set(i, prefix + args[4]);
+            }
+        }
+
         // Clean up the last line of PKG_ACC and PKG_DEF blocks.
         // Not really necessary since a blank line follows.
         boolean inBlock = false;
--- a/jdk/src/java.base/share/classes/com/sun/crypto/provider/CipherCore.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/src/java.base/share/classes/com/sun/crypto/provider/CipherCore.java	Mon Aug 29 08:53:32 2016 -0700
@@ -986,8 +986,9 @@
             if (padding != null) {
                 int padStart = padding.unpad(outWithPadding, 0, outLen);
                 if (padStart < 0) {
-                    throw new BadPaddingException("Given final block not "
-                                                  + "properly padded");
+                    throw new BadPaddingException("Given final block not " +
+                    "properly padded. Such issues can arise if a bad key " +
+                    "is used during decryption.");
                 }
                 outLen = padStart;
             }
--- a/jdk/src/java.base/share/classes/java/lang/Class.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/src/java.base/share/classes/java/lang/Class.java	Mon Aug 29 08:53:32 2016 -0700
@@ -331,12 +331,6 @@
      * Note that this method does not check whether the requested class
      * is accessible to its caller.
      *
-     * <p> If the {@code loader} is {@code null}, and a security
-     * manager is present, and the caller's class loader is not null, then this
-     * method calls the security manager's {@code checkPermission} method
-     * with a {@code RuntimePermission("getClassLoader")} permission to
-     * ensure it's ok to access the bootstrap class loader.
-     *
      * @param name       fully qualified name of the desired class
      * @param initialize if {@code true} the class will be initialized.
      *                   See Section 12.4 of <em>The Java Language Specification</em>.
@@ -348,6 +342,11 @@
      *            by this method fails
      * @exception ClassNotFoundException if the class cannot be located by
      *            the specified class loader
+     * @exception SecurityException
+     *            if a security manager is present, and the {@code loader} is
+     *            {@code null}, and the caller's class loader is not
+     *            {@code null}, and the caller does not have the
+     *            {@link RuntimePermission}{@code ("getClassLoader")}
      *
      * @see       java.lang.Class#forName(String)
      * @see       java.lang.ClassLoader
@@ -782,22 +781,17 @@
      * null in such implementations if this class was loaded by the bootstrap
      * class loader.
      *
-     * <p> If a security manager is present, and the caller's class loader is
-     * not null and the caller's class loader is not the same as or an ancestor of
-     * the class loader for the class whose class loader is requested, then
-     * this method calls the security manager's {@code checkPermission}
-     * method with a {@code RuntimePermission("getClassLoader")}
-     * permission to ensure it's ok to access the class loader for the class.
-     *
      * <p>If this object
      * represents a primitive type or void, null is returned.
      *
      * @return  the class loader that loaded the class or interface
      *          represented by this object.
-     * @throws SecurityException
-     *    if a security manager exists and its
-     *    {@code checkPermission} method denies
-     *    access to the class loader for the class.
+     * @throws  SecurityException
+     *          if a security manager is present, and the caller's class loader
+     *          is not {@code null} and is not the same as or an ancestor of the
+     *          class loader for the class whose class loader is requested,
+     *          and the caller does not have the
+     *          {@link RuntimePermission}{@code ("getClassLoader")}
      * @see java.lang.ClassLoader
      * @see SecurityManager#checkPermission
      * @see java.lang.RuntimePermission
--- a/jdk/src/java.base/share/classes/java/lang/ClassLoader.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/src/java.base/share/classes/java/lang/ClassLoader.java	Mon Aug 29 08:53:32 2016 -0700
@@ -1537,22 +1537,13 @@
      * will return <tt>null</tt> in such implementations if this class loader's
      * parent is the bootstrap class loader.
      *
-     * <p> If a security manager is present, and the invoker's class loader is
-     * not <tt>null</tt> and is not an ancestor of this class loader, then this
-     * method invokes the security manager's {@link
-     * SecurityManager#checkPermission(java.security.Permission)
-     * <tt>checkPermission</tt>} method with a {@link
-     * RuntimePermission#RuntimePermission(String)
-     * <tt>RuntimePermission("getClassLoader")</tt>} permission to verify
-     * access to the parent class loader is permitted.  If not, a
-     * <tt>SecurityException</tt> will be thrown.  </p>
-     *
      * @return  The parent <tt>ClassLoader</tt>
      *
      * @throws  SecurityException
-     *          If a security manager exists and its <tt>checkPermission</tt>
-     *          method doesn't allow access to this class loader's parent class
-     *          loader.
+     *          If a security manager is present, and the caller's class loader
+     *          is not {@code null} and is not an ancestor of this class loader,
+     *          and the caller does not have the
+     *          {@link RuntimePermission}{@code ("getClassLoader")}
      *
      * @since  1.2
      */
@@ -1590,12 +1581,11 @@
      * @return  The platform {@code ClassLoader}.
      *
      * @throws  SecurityException
-     *          If a security manager exists and the caller's class loader is
-     *          not {@code null} and the caller's class loader is not the same
+     *          If a security manager is present, and the caller's class loader is
+     *          not {@code null}, and the caller's class loader is not the same
      *          as or an ancestor of the platform class loader,
-     *          and the {@link SecurityManager#checkPermission(java.security.Permission)
-     *          checkPermission} method denies {@code RuntimePermission("getClassLoader")}
-     *          to access the platform class loader.
+     *          and the caller does not have the
+     *          {@link RuntimePermission}{@code ("getClassLoader")}
      *
      * @since 9
      */
@@ -1636,17 +1626,6 @@
      * If circular initialization of the system class loader is detected then
      * an unspecified error or exception is thrown.
      *
-     * <p> If a security manager is present, and the invoker's class loader is
-     * not <tt>null</tt> and the invoker's class loader is not the same as or
-     * an ancestor of the system class loader, then this method invokes the
-     * security manager's {@link
-     * SecurityManager#checkPermission(java.security.Permission)
-     * <tt>checkPermission</tt>} method with a {@link
-     * RuntimePermission#RuntimePermission(String)
-     * <tt>RuntimePermission("getClassLoader")</tt>} permission to verify
-     * access to the system class loader.  If not, a
-     * <tt>SecurityException</tt> will be thrown.  </p>
-     *
      * @implNote The system property to override the system class loader is not
      * examined until the VM is almost fully initialized. Code that executes
      * this method during startup should take care not to cache the return
@@ -1656,8 +1635,10 @@
      *          <tt>null</tt> if none
      *
      * @throws  SecurityException
-     *          If a security manager exists and its <tt>checkPermission</tt>
-     *          method doesn't allow access to the system class loader.
+     *          If a security manager is present, and the caller's class loader
+     *          is not {@code null} and is not the same as or an ancestor of the
+     *          system class loader, and the caller does not have the
+     *          {@link RuntimePermission}{@code ("getClassLoader")}
      *
      * @throws  IllegalStateException
      *          If invoked recursively during the construction of the class
--- a/jdk/src/java.base/share/classes/java/lang/Math.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/src/java.base/share/classes/java/lang/Math.java	Mon Aug 29 08:53:32 2016 -0700
@@ -1370,8 +1370,13 @@
      * result is positive zero.
      * <li>If the argument is infinite, the result is positive infinity.
      * <li>If the argument is NaN, the result is NaN.</ul>
-     * In other words, the result is the same as the value of the expression:
-     * <p>{@code Float.intBitsToFloat(0x7fffffff & Float.floatToIntBits(a))}
+     *
+     * @apiNote As implied by the above, one valid implementation of
+     * this method is given by the expression below which computes a
+     * {@code float} with the same exponent and significand as the
+     * argument but with a guaranteed zero sign bit indicating a
+     * positive value:<br>
+     * {@code Float.intBitsToFloat(0x7fffffff & Float.floatToRawIntBits(a))}
      *
      * @param   a   the argument whose absolute value is to be determined
      * @return  the absolute value of the argument.
@@ -1389,8 +1394,13 @@
      * is positive zero.
      * <li>If the argument is infinite, the result is positive infinity.
      * <li>If the argument is NaN, the result is NaN.</ul>
-     * In other words, the result is the same as the value of the expression:
-     * <p>{@code Double.longBitsToDouble((Double.doubleToLongBits(a)<<1)>>>1)}
+     *
+     * @apiNote As implied by the above, one valid implementation of
+     * this method is given by the expression below which computes a
+     * {@code double} with the same exponent and significand as the
+     * argument but with a guaranteed zero sign bit indicating a
+     * positive value:<br>
+     * {@code Double.longBitsToDouble((Double.doubleToRawLongBits(a)<<1)>>>1)}
      *
      * @param   a   the argument whose absolute value is to be determined
      * @return  the absolute value of the argument.
--- a/jdk/src/java.base/share/classes/java/lang/StrictMath.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/src/java.base/share/classes/java/lang/StrictMath.java	Mon Aug 29 08:53:32 2016 -0700
@@ -1070,8 +1070,13 @@
      * result is positive zero.
      * <li>If the argument is infinite, the result is positive infinity.
      * <li>If the argument is NaN, the result is NaN.</ul>
-     * In other words, the result is the same as the value of the expression:
-     * <p>{@code Float.intBitsToFloat(0x7fffffff & Float.floatToIntBits(a))}
+     *
+     * @apiNote As implied by the above, one valid implementation of
+     * this method is given by the expression below which computes a
+     * {@code float} with the same exponent and significand as the
+     * argument but with a guaranteed zero sign bit indicating a
+     * positive value: <br>
+     * {@code Float.intBitsToFloat(0x7fffffff & Float.floatToRawIntBits(a))}
      *
      * @param   a   the argument whose absolute value is to be determined
      * @return  the absolute value of the argument.
@@ -1089,8 +1094,13 @@
      * is positive zero.
      * <li>If the argument is infinite, the result is positive infinity.
      * <li>If the argument is NaN, the result is NaN.</ul>
-     * In other words, the result is the same as the value of the expression:
-     * <p>{@code Double.longBitsToDouble((Double.doubleToLongBits(a)<<1)>>>1)}
+     *
+     * @apiNote As implied by the above, one valid implementation of
+     * this method is given by the expression below which computes a
+     * {@code double} with the same exponent and significand as the
+     * argument but with a guaranteed zero sign bit indicating a
+     * positive value: <br>
+     * {@code Double.longBitsToDouble((Double.doubleToRawLongBits(a)<<1)>>>1)}
      *
      * @param   a   the argument whose absolute value is to be determined
      * @return  the absolute value of the argument.
--- a/jdk/src/java.base/share/classes/java/lang/Thread.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/src/java.base/share/classes/java/lang/Thread.java	Mon Aug 29 08:53:32 2016 -0700
@@ -1507,28 +1507,25 @@
     }
 
     /**
-     * Returns the context ClassLoader for this Thread. The context
-     * ClassLoader is provided by the creator of the thread for use
+     * Returns the context {@code ClassLoader} for this thread. The context
+     * {@code ClassLoader} is provided by the creator of the thread for use
      * by code running in this thread when loading classes and resources.
      * If not {@linkplain #setContextClassLoader set}, the default is the
-     * ClassLoader context of the parent Thread. The context ClassLoader of the
+     * {@code ClassLoader} context of the parent thread. The context
+     * {@code ClassLoader} of the
      * primordial thread is typically set to the class loader used to load the
      * application.
      *
-     * <p>If a security manager is present, and the invoker's class loader is not
-     * {@code null} and is not the same as or an ancestor of the context class
-     * loader, then this method invokes the security manager's {@link
-     * SecurityManager#checkPermission(java.security.Permission) checkPermission}
-     * method with a {@link RuntimePermission RuntimePermission}{@code
-     * ("getClassLoader")} permission to verify that retrieval of the context
-     * class loader is permitted.
      *
-     * @return  the context ClassLoader for this Thread, or {@code null}
+     * @return  the context {@code ClassLoader} for this thread, or {@code null}
      *          indicating the system class loader (or, failing that, the
      *          bootstrap class loader)
      *
      * @throws  SecurityException
-     *          if the current thread cannot get the context ClassLoader
+     *          if a security manager is present, and the caller's class loader
+     *          is not {@code null} and is not the same as or an ancestor of the
+     *          context class loader, and the caller does not have the
+     *          {@link RuntimePermission}{@code ("getClassLoader")}
      *
      * @since 1.2
      */
--- a/jdk/src/java.base/share/classes/java/lang/invoke/BoundMethodHandle.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/src/java.base/share/classes/java/lang/invoke/BoundMethodHandle.java	Mon Aug 29 08:53:32 2016 -0700
@@ -497,6 +497,10 @@
                         String shortTypes = LambdaForm.shortenSignature(types);
                         String className = SPECIES_CLASS_PREFIX + shortTypes;
                         Class<?> c = BootLoader.loadClassOrNull(className);
+                        if (TRACE_RESOLVE) {
+                            System.out.println("[BMH_RESOLVE] " + shortTypes +
+                                    (c != null ? " (success)" : " (fail)") );
+                        }
                         if (c != null) {
                             return c.asSubclass(BoundMethodHandle.class);
                         } else {
--- a/jdk/src/java.base/share/classes/java/lang/invoke/DirectMethodHandle.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/src/java.base/share/classes/java/lang/invoke/DirectMethodHandle.java	Mon Aug 29 08:53:32 2016 -0700
@@ -492,7 +492,7 @@
     }
 
     // Caching machinery for field accessors:
-    private static final byte
+    static final byte
             AF_GETFIELD        = 0,
             AF_PUTFIELD        = 1,
             AF_GETSTATIC       = 2,
@@ -502,7 +502,7 @@
             AF_LIMIT           = 6;
     // Enumerate the different field kinds using Wrapper,
     // with an extra case added for checked references.
-    private static final int
+    static final int
             FT_LAST_WRAPPER    = Wrapper.COUNT-1,
             FT_UNCHECKED_REF   = Wrapper.OBJECT.ordinal(),
             FT_CHECKED_REF     = FT_LAST_WRAPPER+1,
@@ -515,7 +515,7 @@
     @Stable
     private static final LambdaForm[] ACCESSOR_FORMS
             = new LambdaForm[afIndex(AF_LIMIT, false, 0)];
-    private static int ftypeKind(Class<?> ftype) {
+    static int ftypeKind(Class<?> ftype) {
         if (ftype.isPrimitive())
             return Wrapper.forPrimitiveType(ftype).ordinal();
         else if (VerifyType.isNullReferenceConversion(Object.class, ftype))
@@ -566,7 +566,64 @@
 
     private static final Wrapper[] ALL_WRAPPERS = Wrapper.values();
 
-    private static LambdaForm makePreparedFieldLambdaForm(byte formOp, boolean isVolatile, int ftypeKind) {
+    private static Kind getFieldKind(boolean isGetter, boolean isVolatile, Wrapper wrapper) {
+        if (isGetter) {
+            if (isVolatile) {
+                switch (wrapper) {
+                    case BOOLEAN: return GET_BOOLEAN_VOLATILE;
+                    case BYTE:    return GET_BYTE_VOLATILE;
+                    case SHORT:   return GET_SHORT_VOLATILE;
+                    case CHAR:    return GET_CHAR_VOLATILE;
+                    case INT:     return GET_INT_VOLATILE;
+                    case LONG:    return GET_LONG_VOLATILE;
+                    case FLOAT:   return GET_FLOAT_VOLATILE;
+                    case DOUBLE:  return GET_DOUBLE_VOLATILE;
+                    case OBJECT:  return GET_OBJECT_VOLATILE;
+                }
+            } else {
+                switch (wrapper) {
+                    case BOOLEAN: return GET_BOOLEAN;
+                    case BYTE:    return GET_BYTE;
+                    case SHORT:   return GET_SHORT;
+                    case CHAR:    return GET_CHAR;
+                    case INT:     return GET_INT;
+                    case LONG:    return GET_LONG;
+                    case FLOAT:   return GET_FLOAT;
+                    case DOUBLE:  return GET_DOUBLE;
+                    case OBJECT:  return GET_OBJECT;
+                }
+            }
+        } else {
+            if (isVolatile) {
+                switch (wrapper) {
+                    case BOOLEAN: return PUT_BOOLEAN_VOLATILE;
+                    case BYTE:    return PUT_BYTE_VOLATILE;
+                    case SHORT:   return PUT_SHORT_VOLATILE;
+                    case CHAR:    return PUT_CHAR_VOLATILE;
+                    case INT:     return PUT_INT_VOLATILE;
+                    case LONG:    return PUT_LONG_VOLATILE;
+                    case FLOAT:   return PUT_FLOAT_VOLATILE;
+                    case DOUBLE:  return PUT_DOUBLE_VOLATILE;
+                    case OBJECT:  return PUT_OBJECT_VOLATILE;
+                }
+            } else {
+                switch (wrapper) {
+                    case BOOLEAN: return PUT_BOOLEAN;
+                    case BYTE:    return PUT_BYTE;
+                    case SHORT:   return PUT_SHORT;
+                    case CHAR:    return PUT_CHAR;
+                    case INT:     return PUT_INT;
+                    case LONG:    return PUT_LONG;
+                    case FLOAT:   return PUT_FLOAT;
+                    case DOUBLE:  return PUT_DOUBLE;
+                    case OBJECT:  return PUT_OBJECT;
+                }
+            }
+        }
+        throw new AssertionError("Invalid arguments");
+    }
+
+    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);
@@ -576,24 +633,14 @@
         assert(ftypeKind(needsCast ? String.class : ft) == ftypeKind);
 
         // 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");
-        }
+        Kind kind = getFieldKind(isGetter, isVolatile, fw);
 
         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, nameBuilder.toString(), linkerType, REF_invokeVirtual);
+        MemberName linker = new MemberName(Unsafe.class, kind.methodName, linkerType, REF_invokeVirtual);
         try {
             linker = IMPL_NAMES.resolveOrFail(REF_invokeVirtual, linker, null, NoSuchMethodException.class);
         } catch (ReflectiveOperationException ex) {
@@ -620,6 +667,7 @@
         final int F_HOLDER  = (isStatic ? nameCursor++ : -1);  // static base if any
         final int F_OFFSET  = nameCursor++;  // Either static offset or field offset.
         final int OBJ_CHECK = (OBJ_BASE >= 0 ? nameCursor++ : -1);
+        final int U_HOLDER  = nameCursor++;  // UNSAFE holder
         final int INIT_BAR  = (needsInit ? nameCursor++ : -1);
         final int PRE_CAST  = (needsCast && !isGetter ? nameCursor++ : -1);
         final int LINKER_CALL = nameCursor++;
@@ -632,7 +680,7 @@
             names[PRE_CAST] = new Name(NF_checkCast, names[DMH_THIS], names[SET_VALUE]);
         Object[] outArgs = new Object[1 + linkerType.parameterCount()];
         assert(outArgs.length == (isGetter ? 3 : 4));
-        outArgs[0] = UNSAFE;
+        outArgs[0] = names[U_HOLDER] = new Name(NF_UNSAFE);
         if (isStatic) {
             outArgs[1] = names[F_HOLDER]  = new Name(NF_staticBase, names[DMH_THIS]);
             outArgs[2] = names[F_OFFSET]  = new Name(NF_staticOffset, names[DMH_THIS]);
@@ -650,6 +698,7 @@
         for (Name n : names)  assert(n != null);
         // add some detail to the lambdaForm debugname,
         // significant only for debugging
+        StringBuilder nameBuilder = new StringBuilder(kind.methodName);
         if (isStatic) {
             nameBuilder.append("Static");
         } else {
@@ -657,7 +706,12 @@
         }
         if (needsCast)  nameBuilder.append("Cast");
         if (needsInit)  nameBuilder.append("Init");
-        return new LambdaForm(nameBuilder.toString(), ARG_LIMIT, names, RESULT);
+        if (needsCast || needsInit) {
+            // can't use the pre-generated form when casting and/or initializing
+            return new LambdaForm(nameBuilder.toString(), ARG_LIMIT, names, RESULT);
+        } else {
+            return new LambdaForm(nameBuilder.toString(), ARG_LIMIT, names, RESULT, kind);
+        }
     }
 
     /**
@@ -674,7 +728,8 @@
             NF_staticOffset,
             NF_checkCast,
             NF_allocateInstance,
-            NF_constructorMethod;
+            NF_constructorMethod,
+            NF_UNSAFE;
     static {
         try {
             NamedFunction nfs[] = {
@@ -697,7 +752,9 @@
                     NF_allocateInstance = new NamedFunction(DirectMethodHandle.class
                             .getDeclaredMethod("allocateInstance", Object.class)),
                     NF_constructorMethod = new NamedFunction(DirectMethodHandle.class
-                            .getDeclaredMethod("constructorMethod", Object.class))
+                            .getDeclaredMethod("constructorMethod", Object.class)),
+                    NF_UNSAFE = new NamedFunction(new MemberName(MethodHandleStatics.class
+                            .getDeclaredField("UNSAFE")))
             };
             // Each nf must be statically invocable or we get tied up in our bootstraps.
             assert(InvokerBytecodeGenerator.isStaticallyInvocable(nfs));
--- a/jdk/src/java.base/share/classes/java/lang/invoke/GenerateJLIClassesHelper.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/src/java.base/share/classes/java/lang/invoke/GenerateJLIClassesHelper.java	Mon Aug 29 08:53:32 2016 -0700
@@ -28,9 +28,11 @@
 import java.util.Map;
 import jdk.internal.org.objectweb.asm.ClassWriter;
 import jdk.internal.org.objectweb.asm.Opcodes;
-
 import java.util.ArrayList;
 import java.util.HashSet;
+import sun.invoke.util.Wrapper;
+
+import static java.lang.invoke.MethodHandleNatives.Constants.*;
 
 /**
  * Helper class to assist the GenerateJLIClassesPlugin to get access to
@@ -66,14 +68,38 @@
 
     static byte[] generateDirectMethodHandleHolderClassBytes(String className,
             MethodType[] methodTypes, int[] types) {
-        LambdaForm[] forms = new LambdaForm[methodTypes.length];
-        String[] names = new String[methodTypes.length];
-        for (int i = 0; i < forms.length; i++) {
-            forms[i] = DirectMethodHandle.makePreparedLambdaForm(methodTypes[i],
-                                                                 types[i]);
-            names[i] = forms[i].kind.defaultLambdaName;
+        ArrayList<LambdaForm> forms = new ArrayList<>();
+        ArrayList<String> names = new ArrayList<>();
+        for (int i = 0; i < methodTypes.length; i++) {
+            LambdaForm form = DirectMethodHandle
+                    .makePreparedLambdaForm(methodTypes[i], types[i]);
+            forms.add(form);
+            names.add(form.kind.defaultLambdaName);
         }
-        return generateCodeBytesForLFs(className, names, forms);
+        for (Wrapper wrapper : Wrapper.values()) {
+            if (wrapper == Wrapper.VOID) {
+                continue;
+            }
+            for (byte b = DirectMethodHandle.AF_GETFIELD; b < DirectMethodHandle.AF_LIMIT; b++) {
+                int ftype = DirectMethodHandle.ftypeKind(wrapper.primitiveType());
+                LambdaForm form = DirectMethodHandle
+                        .makePreparedFieldLambdaForm(b, /*isVolatile*/false, ftype);
+                if (form.kind != LambdaForm.Kind.GENERIC) {
+                    forms.add(form);
+                    names.add(form.kind.defaultLambdaName);
+                }
+                // volatile
+                form = DirectMethodHandle
+                        .makePreparedFieldLambdaForm(b, /*isVolatile*/true, ftype);
+                if (form.kind != LambdaForm.Kind.GENERIC) {
+                    forms.add(form);
+                    names.add(form.kind.defaultLambdaName);
+                }
+            }
+        }
+        return generateCodeBytesForLFs(className,
+                names.toArray(new String[0]),
+                forms.toArray(new LambdaForm[0]));
     }
 
     static byte[] generateDelegatingMethodHandleHolderClassBytes(String className,
@@ -107,6 +133,34 @@
                 forms.toArray(new LambdaForm[0]));
     }
 
+    static byte[] generateInvokersHolderClassBytes(String className,
+            MethodType[] methodTypes) {
+
+        HashSet<MethodType> dedupSet = new HashSet<>();
+        ArrayList<LambdaForm> forms = new ArrayList<>();
+        ArrayList<String> names = new ArrayList<>();
+        int[] types = {
+            MethodTypeForm.LF_EX_LINKER,
+            MethodTypeForm.LF_EX_INVOKER,
+            MethodTypeForm.LF_GEN_LINKER,
+            MethodTypeForm.LF_GEN_INVOKER
+        };
+        for (int i = 0; i < methodTypes.length; i++) {
+            // generate methods representing invokers of the specified type
+            if (dedupSet.add(methodTypes[i])) {
+                for (int type : types) {
+                    LambdaForm invokerForm = Invokers.invokeHandleForm(methodTypes[i],
+                            /*customized*/false, type);
+                    forms.add(invokerForm);
+                    names.add(invokerForm.kind.defaultLambdaName);
+                }
+            }
+        }
+        return generateCodeBytesForLFs(className,
+                names.toArray(new String[0]),
+                forms.toArray(new LambdaForm[0]));
+    }
+
     /*
      * Generate customized code for a set of LambdaForms of specified types into
      * a class with a specified name.
@@ -166,4 +220,5 @@
                          BoundMethodHandle.Factory.generateConcreteBMHClassBytes(
                                  shortTypes, types, className));
     }
+
 }
--- a/jdk/src/java.base/share/classes/java/lang/invoke/InvokerBytecodeGenerator.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/src/java.base/share/classes/java/lang/invoke/InvokerBytecodeGenerator.java	Mon Aug 29 08:53:32 2016 -0700
@@ -607,7 +607,10 @@
     private static MemberName resolveFrom(String name, MethodType type, Class<?> holder) {
         MemberName member = new MemberName(holder, name, type, REF_invokeStatic);
         MemberName resolvedMember = MemberName.getFactory().resolveOrNull(REF_invokeStatic, member, holder);
-
+        if (TRACE_RESOLVE) {
+            System.out.println("[LF_RESOLVE] " + holder.getName() + " " + name + " " +
+                    shortenSignature(basicTypeSignature(type)) + (resolvedMember != null ? " (success)" : " (fail)") );
+        }
         return resolvedMember;
     }
 
@@ -629,6 +632,28 @@
                 name = name + "_" + form.returnType().basicTypeChar();
                 return resolveFrom(name, invokerType, LambdaForm.Holder.class);
             }
+            case EXACT_INVOKER:             // fall-through
+            case EXACT_LINKER:              // fall-through
+            case GENERIC_INVOKER:           // fall-through
+            case GENERIC_LINKER:            return resolveFrom(name, invokerType.basicType(), Invokers.Holder.class);
+            case GET_OBJECT:                // fall-through
+            case GET_BOOLEAN:               // fall-through
+            case GET_BYTE:                  // fall-through
+            case GET_CHAR:                  // fall-through
+            case GET_SHORT:                 // fall-through
+            case GET_INT:                   // fall-through
+            case GET_LONG:                  // fall-through
+            case GET_FLOAT:                 // fall-through
+            case GET_DOUBLE:                // fall-through
+            case PUT_OBJECT:                // fall-through
+            case PUT_BOOLEAN:               // fall-through
+            case PUT_BYTE:                  // fall-through
+            case PUT_CHAR:                  // fall-through
+            case PUT_SHORT:                 // fall-through
+            case PUT_INT:                   // fall-through
+            case PUT_LONG:                  // fall-through
+            case PUT_FLOAT:                 // fall-through
+            case PUT_DOUBLE:                // fall-through
             case DIRECT_INVOKE_INTERFACE:   // fall-through
             case DIRECT_INVOKE_SPECIAL:     // fall-through
             case DIRECT_INVOKE_STATIC:      // fall-through
--- a/jdk/src/java.base/share/classes/java/lang/invoke/Invokers.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/src/java.base/share/classes/java/lang/invoke/Invokers.java	Mon Aug 29 08:53:32 2016 -0700
@@ -36,6 +36,7 @@
 import static java.lang.invoke.MethodHandleNatives.Constants.*;
 import static java.lang.invoke.MethodHandles.Lookup.IMPL_LOOKUP;
 import static java.lang.invoke.LambdaForm.*;
+import static java.lang.invoke.LambdaForm.Kind.*;
 
 /**
  * Construction and caching of often-used invokers.
@@ -254,7 +255,7 @@
      * @param which bit-encoded 0x01 whether it is a CP adapter ("linker") or MHs.invoker value ("invoker");
      *                          0x02 whether it is for invokeExact or generic invoke
      */
-    private static LambdaForm invokeHandleForm(MethodType mtype, boolean customized, int which) {
+    static LambdaForm invokeHandleForm(MethodType mtype, boolean customized, int which) {
         boolean isCached;
         if (!customized) {
             mtype = mtype.basicType();  // normalize Z to I, String to Object, etc.
@@ -263,12 +264,12 @@
             isCached = false;  // maybe cache if mtype == mtype.basicType()
         }
         boolean isLinker, isGeneric;
-        String debugName;
+        Kind kind;
         switch (which) {
-        case MethodTypeForm.LF_EX_LINKER:   isLinker = true;  isGeneric = false; debugName = "invokeExact_MT"; break;
-        case MethodTypeForm.LF_EX_INVOKER:  isLinker = false; isGeneric = false; debugName = "exactInvoker"; break;
-        case MethodTypeForm.LF_GEN_LINKER:  isLinker = true;  isGeneric = true;  debugName = "invoke_MT"; break;
-        case MethodTypeForm.LF_GEN_INVOKER: isLinker = false; isGeneric = true;  debugName = "invoker"; break;
+        case MethodTypeForm.LF_EX_LINKER:   isLinker = true;  isGeneric = false; kind = EXACT_LINKER; break;
+        case MethodTypeForm.LF_EX_INVOKER:  isLinker = false; isGeneric = false; kind = EXACT_INVOKER; break;
+        case MethodTypeForm.LF_GEN_LINKER:  isLinker = true;  isGeneric = true;  kind = GENERIC_LINKER; break;
+        case MethodTypeForm.LF_GEN_INVOKER: isLinker = false; isGeneric = true;  kind = GENERIC_INVOKER; break;
         default: throw new InternalError();
         }
         LambdaForm lform;
@@ -323,7 +324,11 @@
             names[CHECK_CUSTOM] = new Name(NF_checkCustomized, outArgs[0]);
         }
         names[LINKER_CALL] = new Name(outCallType, outArgs);
-        lform = new LambdaForm(debugName, INARG_LIMIT, names);
+        if (customized) {
+            lform = new LambdaForm(kind.defaultLambdaName, INARG_LIMIT, names);
+        } else {
+            lform = new LambdaForm(kind.defaultLambdaName, INARG_LIMIT, names, kind);
+        }
         if (isLinker)
             lform.compileToBytecode();  // JVM needs a real methodOop
         if (isCached)
@@ -614,4 +619,15 @@
             }
         }
     }
+
+    static {
+        // The Holder class will contain pre-generated Invokers resolved
+        // speculatively using MemberName.getFactory().resolveOrNull. However, that
+        // doesn't initialize the class, which subtly breaks inlining etc. By forcing
+        // initialization of the Holder class we avoid these issues.
+        UNSAFE.ensureClassInitialized(Holder.class);
+    }
+
+    /* Placeholder class for Invokers generated ahead of time */
+    final class Holder {}
 }
--- a/jdk/src/java.base/share/classes/java/lang/invoke/LambdaForm.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/src/java.base/share/classes/java/lang/invoke/LambdaForm.java	Mon Aug 29 08:53:32 2016 -0700
@@ -275,12 +275,52 @@
         BOUND_REINVOKER("BMH.reinvoke"),
         REINVOKER("MH.reinvoke"),
         DELEGATE("MH.delegate"),
+        EXACT_LINKER("MH.invokeExact_MT"),
+        EXACT_INVOKER("MH.exactInvoker"),
+        GENERIC_LINKER("MH.invoke_MT"),
+        GENERIC_INVOKER("MH.invoker"),
         DIRECT_INVOKE_VIRTUAL("DMH.invokeVirtual"),
         DIRECT_INVOKE_SPECIAL("DMH.invokeSpecial"),
         DIRECT_INVOKE_STATIC("DMH.invokeStatic"),
         DIRECT_NEW_INVOKE_SPECIAL("DMH.newInvokeSpecial"),
         DIRECT_INVOKE_INTERFACE("DMH.invokeInterface"),
-        DIRECT_INVOKE_STATIC_INIT("DMH.invokeStaticInit");
+        DIRECT_INVOKE_STATIC_INIT("DMH.invokeStaticInit"),
+        GET_OBJECT("getObject"),
+        PUT_OBJECT("putObject"),
+        GET_OBJECT_VOLATILE("getObjectVolatile"),
+        PUT_OBJECT_VOLATILE("putObjectVolatile"),
+        GET_INT("getInt"),
+        PUT_INT("putInt"),
+        GET_INT_VOLATILE("getIntVolatile"),
+        PUT_INT_VOLATILE("putIntVolatile"),
+        GET_BOOLEAN("getBoolean"),
+        PUT_BOOLEAN("putBoolean"),
+        GET_BOOLEAN_VOLATILE("getBooleanVolatile"),
+        PUT_BOOLEAN_VOLATILE("putBooleanVolatile"),
+        GET_BYTE("getByte"),
+        PUT_BYTE("putByte"),
+        GET_BYTE_VOLATILE("getByteVolatile"),
+        PUT_BYTE_VOLATILE("putByteVolatile"),
+        GET_CHAR("getChar"),
+        PUT_CHAR("putChar"),
+        GET_CHAR_VOLATILE("getCharVolatile"),
+        PUT_CHAR_VOLATILE("putCharVolatile"),
+        GET_SHORT("getShort"),
+        PUT_SHORT("putShort"),
+        GET_SHORT_VOLATILE("getShortVolatile"),
+        PUT_SHORT_VOLATILE("putShortVolatile"),
+        GET_LONG("getLong"),
+        PUT_LONG("putLong"),
+        GET_LONG_VOLATILE("getLongVolatile"),
+        PUT_LONG_VOLATILE("putLongVolatile"),
+        GET_FLOAT("getFloat"),
+        PUT_FLOAT("putFloat"),
+        GET_FLOAT_VOLATILE("getFloatVolatile"),
+        PUT_FLOAT_VOLATILE("putFloatVolatile"),
+        GET_DOUBLE("getDouble"),
+        PUT_DOUBLE("putDouble"),
+        GET_DOUBLE_VOLATILE("getDoubleVolatile"),
+        PUT_DOUBLE_VOLATILE("putDoubleVolatile");
 
         final String defaultLambdaName;
         final String methodName;
@@ -330,6 +370,10 @@
         this(debugName, arity, names, LAST_RESULT, /*forceInline=*/true, /*customized=*/null, Kind.GENERIC);
     }
     LambdaForm(String debugName,
+               int arity, Name[] names, Kind kind) {
+        this(debugName, arity, names, LAST_RESULT, /*forceInline=*/true, /*customized=*/null, kind);
+    }
+    LambdaForm(String debugName,
                int arity, Name[] names, boolean forceInline) {
         this(debugName, arity, names, LAST_RESULT, forceInline, /*customized=*/null, Kind.GENERIC);
     }
@@ -817,54 +861,6 @@
         }
     }
 
-    private static void computeInitialPreparedForms() {
-        // Find all predefined invokers and associate them with canonical empty lambda forms.
-        for (MemberName m : MemberName.getFactory().getMethods(LambdaForm.class, false, null, null, null)) {
-            if (!m.isStatic() || !m.isPackage())  continue;
-            MethodType mt = m.getMethodType();
-            if (mt.parameterCount() > 0 &&
-                mt.parameterType(0) == MethodHandle.class &&
-                m.getName().startsWith("interpret_")) {
-                String sig = null;
-                assert((sig = basicTypeSignature(mt)) != null &&
-                        m.getName().equals("interpret" + sig.substring(sig.indexOf('_'))));
-                LambdaForm form = new LambdaForm(mt);
-                form.vmentry = m;
-                form = mt.form().setCachedLambdaForm(MethodTypeForm.LF_INTERPRET, form);
-            }
-        }
-    }
-
-    // Set this false to disable use of the interpret_L methods defined in this file.
-    private static final boolean USE_PREDEFINED_INTERPRET_METHODS = true;
-
-    // The following are predefined exact invokers.  The system must build
-    // a separate invoker for each distinct signature.
-    static Object interpret_L(MethodHandle mh) throws Throwable {
-        Object[] av = {mh};
-        String sig = null;
-        assert(argumentTypesMatch(sig = "L_L", av));
-        Object res = mh.form.interpretWithArguments(av);
-        assert(returnTypesMatch(sig, av, res));
-        return res;
-    }
-    static Object interpret_L(MethodHandle mh, Object x1) throws Throwable {
-        Object[] av = {mh, x1};
-        String sig = null;
-        assert(argumentTypesMatch(sig = "LL_L", av));
-        Object res = mh.form.interpretWithArguments(av);
-        assert(returnTypesMatch(sig, av, res));
-        return res;
-    }
-    static Object interpret_L(MethodHandle mh, Object x1, Object x2) throws Throwable {
-        Object[] av = {mh, x1, x2};
-        String sig = null;
-        assert(argumentTypesMatch(sig = "LLL_L", av));
-        Object res = mh.form.interpretWithArguments(av);
-        assert(returnTypesMatch(sig, av, res));
-        return res;
-    }
-
     // The next few routines are called only from assert expressions
     // They verify that the built-in invokers process the correct raw data types.
     private static boolean argumentTypesMatch(String sig, Object[] av) {
@@ -1151,113 +1147,6 @@
             return super.hashCode();
         }
 
-        // Put the predefined NamedFunction invokers into the table.
-        static void initializeInvokers() {
-            for (MemberName m : MemberName.getFactory().getMethods(NamedFunction.class, false, null, null, null)) {
-                if (!m.isStatic() || !m.isPackage())  continue;
-                MethodType type = m.getMethodType();
-                if (type.equals(INVOKER_METHOD_TYPE) &&
-                    m.getName().startsWith("invoke_")) {
-                    String sig = m.getName().substring("invoke_".length());
-                    int arity = LambdaForm.signatureArity(sig);
-                    MethodType srcType = MethodType.genericMethodType(arity);
-                    if (LambdaForm.signatureReturn(sig) == V_TYPE)
-                        srcType = srcType.changeReturnType(void.class);
-                    MethodTypeForm typeForm = srcType.form();
-                    typeForm.setCachedMethodHandle(MethodTypeForm.MH_NF_INV, DirectMethodHandle.make(m));
-                }
-            }
-        }
-
-        // The following are predefined NamedFunction invokers.  The system must build
-        // a separate invoker for each distinct signature.
-        /** void return type invokers. */
-        @Hidden
-        static Object invoke__V(MethodHandle mh, Object[] a) throws Throwable {
-            assert(arityCheck(0, void.class, mh, a));
-            mh.invokeBasic();
-            return null;
-        }
-        @Hidden
-        static Object invoke_L_V(MethodHandle mh, Object[] a) throws Throwable {
-            assert(arityCheck(1, void.class, mh, a));
-            mh.invokeBasic(a[0]);
-            return null;
-        }
-        @Hidden
-        static Object invoke_LL_V(MethodHandle mh, Object[] a) throws Throwable {
-            assert(arityCheck(2, void.class, mh, a));
-            mh.invokeBasic(a[0], a[1]);
-            return null;
-        }
-        @Hidden
-        static Object invoke_LLL_V(MethodHandle mh, Object[] a) throws Throwable {
-            assert(arityCheck(3, void.class, mh, a));
-            mh.invokeBasic(a[0], a[1], a[2]);
-            return null;
-        }
-        @Hidden
-        static Object invoke_LLLL_V(MethodHandle mh, Object[] a) throws Throwable {
-            assert(arityCheck(4, void.class, mh, a));
-            mh.invokeBasic(a[0], a[1], a[2], a[3]);
-            return null;
-        }
-        @Hidden
-        static Object invoke_LLLLL_V(MethodHandle mh, Object[] a) throws Throwable {
-            assert(arityCheck(5, void.class, mh, a));
-            mh.invokeBasic(a[0], a[1], a[2], a[3], a[4]);
-            return null;
-        }
-        /** Object return type invokers. */
-        @Hidden
-        static Object invoke__L(MethodHandle mh, Object[] a) throws Throwable {
-            assert(arityCheck(0, mh, a));
-            return mh.invokeBasic();
-        }
-        @Hidden
-        static Object invoke_L_L(MethodHandle mh, Object[] a) throws Throwable {
-            assert(arityCheck(1, mh, a));
-            return mh.invokeBasic(a[0]);
-        }
-        @Hidden
-        static Object invoke_LL_L(MethodHandle mh, Object[] a) throws Throwable {
-            assert(arityCheck(2, mh, a));
-            return mh.invokeBasic(a[0], a[1]);
-        }
-        @Hidden
-        static Object invoke_LLL_L(MethodHandle mh, Object[] a) throws Throwable {
-            assert(arityCheck(3, mh, a));
-            return mh.invokeBasic(a[0], a[1], a[2]);
-        }
-        @Hidden
-        static Object invoke_LLLL_L(MethodHandle mh, Object[] a) throws Throwable {
-            assert(arityCheck(4, mh, a));
-            return mh.invokeBasic(a[0], a[1], a[2], a[3]);
-        }
-        @Hidden
-        static Object invoke_LLLLL_L(MethodHandle mh, Object[] a) throws Throwable {
-            assert(arityCheck(5, mh, a));
-            return mh.invokeBasic(a[0], a[1], a[2], a[3], a[4]);
-        }
-        private static boolean arityCheck(int arity, MethodHandle mh, Object[] a) {
-            return arityCheck(arity, Object.class, mh, a);
-        }
-        private static boolean arityCheck(int arity, Class<?> rtype, MethodHandle mh, Object[] a) {
-            assert(a.length == arity)
-                    : Arrays.asList(a.length, arity);
-            assert(mh.type().basicType() == MethodType.genericMethodType(arity).changeReturnType(rtype))
-                    : Arrays.asList(mh, rtype, arity);
-            MemberName member = mh.internalMemberName();
-            if (isInvokeBasic(member)) {
-                assert(arity > 0);
-                assert(a[0] instanceof MethodHandle);
-                MethodHandle mh2 = (MethodHandle) a[0];
-                assert(mh2.type().basicType() == MethodType.genericMethodType(arity-1).changeReturnType(rtype))
-                        : Arrays.asList(member, mh2, rtype, arity);
-            }
-            return true;
-        }
-
         static final MethodType INVOKER_METHOD_TYPE =
             MethodType.methodType(Object.class, MethodHandle.class, Object[].class);
 
@@ -1920,12 +1809,7 @@
             DEBUG_NAME_COUNTERS = null;
     }
 
-    // Put this last, so that previous static inits can run before.
     static {
-        if (USE_PREDEFINED_INTERPRET_METHODS)
-            computeInitialPreparedForms();
-        NamedFunction.initializeInvokers();
-
         // The Holder class will contain pre-generated forms resolved
         // using MemberName.getFactory(). However, that doesn't initialize the
         // class, which subtly breaks inlining etc. By forcing
--- a/jdk/src/java.base/share/classes/java/lang/invoke/MethodHandleImpl.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/src/java.base/share/classes/java/lang/invoke/MethodHandleImpl.java	Mon Aug 29 08:53:32 2016 -0700
@@ -1745,6 +1745,13 @@
                 return GenerateJLIClassesHelper
                         .generateBasicFormsClassBytes(className);
             }
+
+            @Override
+            public byte[] generateInvokersHolderClassBytes(final String className,
+                    MethodType[] methodTypes) {
+                return GenerateJLIClassesHelper
+                        .generateInvokersHolderClassBytes(className, methodTypes);
+            }
         });
     }
 
--- a/jdk/src/java.base/share/classes/java/lang/invoke/MethodHandleStatics.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/src/java.base/share/classes/java/lang/invoke/MethodHandleStatics.java	Mon Aug 29 08:53:32 2016 -0700
@@ -46,6 +46,7 @@
     static final boolean DUMP_CLASS_FILES;
     static final boolean TRACE_INTERPRETER;
     static final boolean TRACE_METHOD_LINKAGE;
+    static final boolean TRACE_RESOLVE;
     static final int COMPILE_THRESHOLD;
     static final boolean LOG_LF_COMPILATION_FAILURE;
     static final int DONT_INLINE_THRESHOLD;
@@ -65,6 +66,8 @@
                 props.getProperty("java.lang.invoke.MethodHandle.TRACE_INTERPRETER"));
         TRACE_METHOD_LINKAGE = Boolean.parseBoolean(
                 props.getProperty("java.lang.invoke.MethodHandle.TRACE_METHOD_LINKAGE"));
+        TRACE_RESOLVE = Boolean.parseBoolean(
+                props.getProperty("java.lang.invoke.MethodHandle.TRACE_RESOLVE"));
         COMPILE_THRESHOLD = Integer.parseInt(
                 props.getProperty("java.lang.invoke.MethodHandle.COMPILE_THRESHOLD", "0"));
         LOG_LF_COMPILATION_FAILURE = Boolean.parseBoolean(
--- a/jdk/src/java.base/share/classes/java/net/HttpCookie.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/src/java.base/share/classes/java/net/HttpCookie.java	Mon Aug 29 08:53:32 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2013, 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
@@ -233,7 +233,7 @@
         // if not specify max-age, this cookie should be
         // discarded when user agent is to be closed, but
         // it is not expired.
-        if (maxAge == MAX_AGE_UNSPECIFIED) return false;
+        if (maxAge < 0) return false;
 
         long deltaSecond = (System.currentTimeMillis() - whenCreated) / 1000;
         if (deltaSecond > maxAge)
@@ -952,7 +952,8 @@
                                    String attrName,
                                    String attrValue) {
                     if (cookie.getMaxAge() == MAX_AGE_UNSPECIFIED) {
-                        cookie.setMaxAge(cookie.expiryDate2DeltaSeconds(attrValue));
+                        long delta = cookie.expiryDate2DeltaSeconds(attrValue);
+                        cookie.setMaxAge(delta > 0 ? delta : 0);
                     }
                 }
             });
--- a/jdk/src/java.base/share/classes/java/time/Duration.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/src/java.base/share/classes/java/time/Duration.java	Mon Aug 29 08:53:32 2016 -0700
@@ -150,10 +150,12 @@
     /**
      * The pattern for parsing.
      */
-    private static final Pattern PATTERN =
+    private static class Lazy {
+        static final Pattern PATTERN =
             Pattern.compile("([-+]?)P(?:([-+]?[0-9]+)D)?" +
                     "(T(?:([-+]?[0-9]+)H)?(?:([-+]?[0-9]+)M)?(?:([-+]?[0-9]+)(?:[.,]([0-9]{0,9}))?S)?)?",
                     Pattern.CASE_INSENSITIVE);
+    }
 
     /**
      * The number of seconds in the duration.
@@ -387,7 +389,7 @@
      */
     public static Duration parse(CharSequence text) {
         Objects.requireNonNull(text, "text");
-        Matcher matcher = PATTERN.matcher(text);
+        Matcher matcher = Lazy.PATTERN.matcher(text);
         if (matcher.matches()) {
             // check for letter T but no time sections
             if (!charMatch(text, matcher.start(3), matcher.end(3), 'T')) {
--- a/jdk/src/java.base/share/classes/java/time/ZoneOffset.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/src/java.base/share/classes/java/time/ZoneOffset.java	Mon Aug 29 08:53:32 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 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
@@ -375,15 +375,15 @@
         } else if ((minutes > 0 && seconds < 0) || (minutes < 0 && seconds > 0)) {
             throw new DateTimeException("Zone offset minutes and seconds must have the same sign");
         }
-        if (Math.abs(minutes) > 59) {
-            throw new DateTimeException("Zone offset minutes not in valid range: abs(value) " +
-                    Math.abs(minutes) + " is not in the range 0 to 59");
+        if (minutes < -59 || minutes > 59) {
+            throw new DateTimeException("Zone offset minutes not in valid range: value " +
+                    minutes + " is not in the range -59 to 59");
         }
-        if (Math.abs(seconds) > 59) {
-            throw new DateTimeException("Zone offset seconds not in valid range: abs(value) " +
-                    Math.abs(seconds) + " is not in the range 0 to 59");
+        if (seconds < -59 || seconds > 59) {
+            throw new DateTimeException("Zone offset seconds not in valid range: value " +
+                    seconds + " is not in the range -59 to 59");
         }
-        if (Math.abs(hours) == 18 && (Math.abs(minutes) > 0 || Math.abs(seconds) > 0)) {
+        if (Math.abs(hours) == 18 && (minutes | seconds) != 0) {
             throw new DateTimeException("Zone offset not in valid range: -18:00 to +18:00");
         }
     }
@@ -411,7 +411,7 @@
      * @throws DateTimeException if the offset is not in the required range
      */
     public static ZoneOffset ofTotalSeconds(int totalSeconds) {
-        if (Math.abs(totalSeconds) > MAX_SECONDS) {
+        if (totalSeconds < -MAX_SECONDS || totalSeconds > MAX_SECONDS) {
             throw new DateTimeException("Zone offset not in valid range: -18:00 to +18:00");
         }
         if (totalSeconds % (15 * SECONDS_PER_MINUTE) == 0) {
@@ -696,11 +696,12 @@
      * The comparison is "consistent with equals", as defined by {@link Comparable}.
      *
      * @param other  the other date to compare to, not null
-     * @return the comparator value, negative if less, postive if greater
+     * @return the comparator value, negative if less, positive if greater
      * @throws NullPointerException if {@code other} is null
      */
     @Override
     public int compareTo(ZoneOffset other) {
+        // abs(totalSeconds) <= MAX_SECONDS, so no overflow can happen here
         return other.totalSeconds - totalSeconds;
     }
 
--- a/jdk/src/java.base/share/classes/java/util/concurrent/ConcurrentHashMap.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/src/java.base/share/classes/java/util/concurrent/ConcurrentHashMap.java	Mon Aug 29 08:53:32 2016 -0700
@@ -4566,7 +4566,10 @@
             boolean modified = false;
             // Use (c instanceof Set) as a hint that lookup in c is as
             // efficient as this view
-            if (c instanceof Set<?> && c.size() > map.table.length) {
+            Node<K,V>[] t;
+            if ((t = map.table) == null) {
+                return false;
+            } else if (c instanceof Set<?> && c.size() > t.length) {
                 for (Iterator<?> it = iterator(); it.hasNext(); ) {
                     if (c.contains(it.next())) {
                         it.remove();
--- a/jdk/src/java.base/share/classes/java/util/jar/JarFile.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/src/java.base/share/classes/java/util/jar/JarFile.java	Mon Aug 29 08:53:32 2016 -0700
@@ -353,7 +353,7 @@
         if (isMultiRelease) {
             return true;
         }
-        if (MULTI_RELEASE_ENABLED && versionMajor != BASE_VERSION_MAJOR) {
+        if (MULTI_RELEASE_ENABLED) {
             try {
                 checkForSpecialAttributes();
             } catch (IOException io) {
@@ -644,7 +644,7 @@
             return signers == null ? null : signers.clone();
         }
         JarFileEntry realEntry() {
-            if (isMultiRelease()) {
+            if (isMultiRelease() && versionMajor != BASE_VERSION_MAJOR) {
                 String entryName = super.getName();
                 return entryName.equals(this.name) ? this : new JarFileEntry(entryName, this);
             }
@@ -960,7 +960,7 @@
                 hasClassPathAttribute = match(CLASSPATH_CHARS, b,
                         CLASSPATH_LASTOCC) != -1;
                 // is this a multi-release jar file
-                if (MULTI_RELEASE_ENABLED && versionMajor != BASE_VERSION_MAJOR) {
+                if (MULTI_RELEASE_ENABLED) {
                     int i = match(MULTIRELEASE_CHARS, b, MULTIRELEASE_LASTOCC);
                     if (i != -1) {
                         i += MULTIRELEASE_CHARS.length;
--- a/jdk/src/java.base/share/classes/javax/crypto/JceSecurity.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/src/java.base/share/classes/javax/crypto/JceSecurity.java	Mon Aug 29 08:53:32 2016 -0700
@@ -29,6 +29,7 @@
 import java.util.jar.*;
 import java.io.*;
 import java.net.URL;
+import java.nio.file.*;
 import java.security.*;
 
 import java.security.Provider.Service;
@@ -206,7 +207,7 @@
 
     static {
         try {
-            NULL_URL = new URL("http://null.sun.com/");
+            NULL_URL = new URL("http://null.oracle.com/");
         } catch (Exception e) {
             throw new RuntimeException(e);
         }
@@ -243,83 +244,94 @@
         }
     }
 
+    // This is called from within an doPrivileged block.
     private static void setupJurisdictionPolicies() throws Exception {
-        String javaHomeDir = System.getProperty("java.home");
-        String sep = File.separator;
-        String pathToPolicyJar = javaHomeDir + sep + "lib" + sep +
-            "security" + sep;
 
-        File exportJar = new File(pathToPolicyJar, "US_export_policy.jar");
-        File importJar = new File(pathToPolicyJar, "local_policy.jar");
+        // Sanity check the crypto.policy Security property.  Single
+        // directory entry, no pseudo-directories (".", "..", leading/trailing
+        // path separators). normalize()/getParent() will help later.
+        String cryptoPolicyProperty = Security.getProperty("crypto.policy");
+        Path cpPath = Paths.get(cryptoPolicyProperty);
 
-        if (!exportJar.exists() || !importJar.exists()) {
-            throw new SecurityException
-                                ("Cannot locate policy or framework files!");
+        if ((cryptoPolicyProperty == null) ||
+                (cpPath.getNameCount() != 1) ||
+                (cpPath.compareTo(cpPath.getFileName()) != 0)) {
+            throw new SecurityException(
+                "Invalid policy directory name format: " +
+                cryptoPolicyProperty);
         }
 
-        // Read jurisdiction policies.
-        CryptoPermissions defaultExport = new CryptoPermissions();
-        CryptoPermissions exemptExport = new CryptoPermissions();
-        loadPolicies(exportJar, defaultExport, exemptExport);
+        // Prepend java.home to get the full path.  normalize() in
+        // case an extra "." or ".." snuck in somehow.
+        String javaHomeProperty = System.getProperty("java.home");
+        Path javaHomePolicyPath = Paths.get(javaHomeProperty, "conf",
+                "security", "policy").normalize();
+        Path cryptoPolicyPath = Paths.get(javaHomeProperty, "conf", "security",
+                "policy", cryptoPolicyProperty).normalize();
 
-        CryptoPermissions defaultImport = new CryptoPermissions();
-        CryptoPermissions exemptImport = new CryptoPermissions();
-        loadPolicies(importJar, defaultImport, exemptImport);
+        if (cryptoPolicyPath.getParent().compareTo(javaHomePolicyPath) != 0) {
+            throw new SecurityException(
+                "Invalid cryptographic jurisdiction policy directory path: " +
+                cryptoPolicyProperty);
+        }
 
-        // Merge the export and import policies for default applications.
-        if (defaultExport.isEmpty() || defaultImport.isEmpty()) {
-            throw new SecurityException("Missing mandatory jurisdiction " +
-                                        "policy files");
+        if (!Files.isDirectory(cryptoPolicyPath)
+                || !Files.isReadable(cryptoPolicyPath)) {
+            throw new SecurityException(
+                "Can't read cryptographic policy directory: " +
+                cryptoPolicyProperty);
         }
-        defaultPolicy = defaultExport.getMinimum(defaultImport);
 
-        // Merge the export and import policies for exempt applications.
-        if (exemptExport.isEmpty())  {
-            exemptPolicy = exemptImport.isEmpty() ? null : exemptImport;
-        } else {
-            exemptPolicy = exemptExport.getMinimum(exemptImport);
-        }
-    }
+        try (DirectoryStream<Path> stream = Files.newDirectoryStream(
+                cryptoPolicyPath, "{default,exempt}_*.policy")) {
+            for (Path entry : stream) {
+                try (InputStream is = new BufferedInputStream(
+                        Files.newInputStream(entry))) {
+                    String filename = entry.getFileName().toString();
 
-    /**
-     * Load the policies from the specified file. Also checks that the
-     * policies are correctly signed.
-     */
-    private static void loadPolicies(File jarPathName,
-                                     CryptoPermissions defaultPolicy,
-                                     CryptoPermissions exemptPolicy)
-        throws Exception {
+                    CryptoPermissions tmpPerms = new CryptoPermissions();
+                    tmpPerms.load(is);
 
-        JarFile jf = new JarFile(jarPathName);
-
-        Enumeration<JarEntry> entries = jf.entries();
-        while (entries.hasMoreElements()) {
-            JarEntry je = entries.nextElement();
-            InputStream is = null;
-            try {
-                if (je.getName().startsWith("default_")) {
-                    is = jf.getInputStream(je);
-                    defaultPolicy.load(is);
-                } else if (je.getName().startsWith("exempt_")) {
-                    is = jf.getInputStream(je);
-                    exemptPolicy.load(is);
-                } else {
-                    continue;
-                }
-            } finally {
-                if (is != null) {
-                    is.close();
+                    if (filename.startsWith("default_")) {
+                        // Did we find a default perms?
+                        defaultPolicy = ((defaultPolicy == null) ? tmpPerms :
+                                defaultPolicy.getMinimum(tmpPerms));
+                    } else if (filename.startsWith("exempt_")) {
+                        // Did we find a exempt perms?
+                        exemptPolicy = ((exemptPolicy == null) ? tmpPerms :
+                                exemptPolicy.getMinimum(tmpPerms));
+                    } else {
+                        // This should never happen.  newDirectoryStream
+                        // should only throw return "{default,exempt}_*.policy"
+                        throw new SecurityException(
+                            "Unexpected jurisdiction policy files in : " +
+                            cryptoPolicyProperty);
+                    }
+                } catch (Exception e) {
+                    throw new SecurityException(
+                        "Couldn't parse jurisdiction policy files in: " +
+                        cryptoPolicyProperty);
                 }
             }
+        } catch (DirectoryIteratorException ex) {
+            // I/O error encountered during the iteration,
+            // the cause is an IOException
+            throw new SecurityException(
+                "Couldn't iterate through the jurisdiction policy files: " +
+                cryptoPolicyProperty);
+        }
 
-            // Enforce the signer restraint, i.e. signer of JCE framework
-            // jar should also be the signer of the two jurisdiction policy
-            // jar files.
-            ProviderVerifier.verifyPolicySigned(je.getCertificates());
+        // Must have a default policy
+        if ((defaultPolicy == null) || defaultPolicy.isEmpty()) {
+            throw new SecurityException(
+                "Missing mandatory jurisdiction policy files: " +
+                cryptoPolicyProperty);
         }
-        // Close and nullify the JarFile reference to help GC.
-        jf.close();
-        jf = null;
+
+        // If there was an empty exempt policy file, ignore it.
+        if ((exemptPolicy != null) && exemptPolicy.isEmpty()) {
+            exemptPolicy = null;
+        }
     }
 
     static CryptoPermissions getDefaultPolicy() {
--- a/jdk/src/java.base/share/classes/jdk/internal/misc/JavaLangInvokeAccess.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/src/java.base/share/classes/jdk/internal/misc/JavaLangInvokeAccess.java	Mon Aug 29 08:53:32 2016 -0700
@@ -46,7 +46,7 @@
     boolean isNative(Object mname);
 
     /**
-     * Returns a {@code byte[]} containing the bytecode for a class implementing
+     * Returns a {@code byte[]} representation of 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.
@@ -55,7 +55,7 @@
             MethodType[] methodTypes, int[] types);
 
     /**
-     * Returns a {@code byte[]} containing the bytecode for a class implementing
+     * Returns a {@code byte[]} representation of a class implementing
      * DelegatingMethodHandles of each {@code MethodType} kind in the
      * {@code methodTypes} argument.  Used by GenerateJLIClassesPlugin to
      * generate such a class during the jlink phase.
@@ -64,7 +64,7 @@
             MethodType[] methodTypes);
 
     /**
-     * Returns a {@code byte[]} containing the bytecode for a BoundMethodHandle
+     * Returns a {@code byte[]} representation of {@code 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
@@ -74,8 +74,15 @@
             final String types);
 
     /**
-     * Returns a {@code byte[]} containing the bytecode for a class implementing
+     * Returns a {@code byte[]} representation of a class implementing
      * the zero and identity forms of all {@code LambdaForm.BasicType}s.
      */
     byte[] generateBasicFormsClassBytes(final String className);
+
+    /**
+     * Returns a {@code byte[]} representation of a class implementing
+     * the invoker forms for the set of supplied {@code methodTypes}.
+     */
+    byte[] generateInvokersHolderClassBytes(String className,
+            MethodType[] methodTypes);
 }
--- a/jdk/src/java.base/share/classes/sun/security/rsa/RSAPadding.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/src/java.base/share/classes/sun/security/rsa/RSAPadding.java	Mon Aug 29 08:53:32 2016 -0700
@@ -253,7 +253,8 @@
     public byte[] pad(byte[] data) throws BadPaddingException {
         if (data.length > maxDataSize) {
             throw new BadPaddingException("Data must be shorter than "
-                + (maxDataSize + 1) + " bytes");
+                + (maxDataSize + 1) + " bytes but received "
+                + data.length + " bytes.");
         }
         switch (type) {
         case PAD_NONE:
@@ -281,7 +282,9 @@
      */
     public byte[] unpad(byte[] padded) throws BadPaddingException {
         if (padded.length != paddedSize) {
-            throw new BadPaddingException("Decryption error");
+            throw new BadPaddingException("Decryption error." +
+                "The padded array length (" + padded.length +
+                ") is not the specified padded size (" + paddedSize + ")");
         }
         switch (type) {
         case PAD_NONE:
--- a/jdk/src/java.base/share/classes/sun/security/ssl/CipherBox.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/src/java.base/share/classes/sun/security/ssl/CipherBox.java	Mon Aug 29 08:53:32 2016 -0700
@@ -493,7 +493,9 @@
 
                 if (protocolVersion.useTLS11PlusSpec()) {
                     if (newLen < blockSize) {
-                        throw new BadPaddingException("invalid explicit IV");
+                        throw new BadPaddingException("The length after " +
+                        "padding removal (" + newLen + ") should be larger " +
+                        "than <" + blockSize + "> since explicit IV used");
                     }
                 }
             }
@@ -504,7 +506,6 @@
         }
     }
 
-
     /*
      * Decrypts a block of data, returning the size of the
      * resulting block if padding was required.  position and limit
@@ -575,7 +576,9 @@
                 // check the explicit IV of TLS v1.1 or later
                 if (protocolVersion.useTLS11PlusSpec()) {
                     if (newLen < blockSize) {
-                        throw new BadPaddingException("invalid explicit IV");
+                        throw new BadPaddingException("The length after " +
+                        "padding removal (" + newLen + ") should be larger " +
+                        "than <" + blockSize + "> since explicit IV used");
                     }
 
                     // reset the position to the end of the decrypted data
@@ -756,7 +759,9 @@
             // so accept that as well
             // v3 does not require any particular value for the other bytes
             if (padLen > blockSize) {
-                throw new BadPaddingException("Invalid SSLv3 padding");
+                throw new BadPaddingException("Padding length (" +
+                padLen + ") of SSLv3 message should not be bigger " +
+                "than the block size (" + blockSize + ")");
             }
         }
         return newLen;
@@ -802,7 +807,9 @@
             // so accept that as well
             // v3 does not require any particular value for the other bytes
             if (padLen > blockSize) {
-                throw new BadPaddingException("Invalid SSLv3 padding");
+                throw new BadPaddingException("Padding length (" +
+                padLen + ") of SSLv3 message should not be bigger " +
+                "than the block size (" + blockSize + ")");
             }
         }
 
@@ -925,7 +932,10 @@
             case AEAD_CIPHER:
                 if (bb.remaining() < (recordIvSize + tagSize)) {
                     throw new BadPaddingException(
-                                        "invalid AEAD cipher fragment");
+                        "Insufficient buffer remaining for AEAD cipher " +
+                        "fragment (" + bb.remaining() + "). Needs to be " +
+                        "more than or equal to IV size (" + recordIvSize +
+                         ") + tag size (" + tagSize + ")");
                 }
 
                 // initialize the AEAD cipher for the unique IV
--- a/jdk/src/java.base/share/classes/sun/util/calendar/ZoneInfo.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/src/java.base/share/classes/sun/util/calendar/ZoneInfo.java	Mon Aug 29 08:53:32 2016 -0700
@@ -27,15 +27,8 @@
 
 import java.io.IOException;
 import java.io.ObjectInputStream;
-import java.lang.ref.SoftReference;
-import java.security.AccessController;
-import java.util.ArrayList;
-import java.util.Arrays;
 import java.util.Date;
-import java.util.List;
-import java.util.Locale;
 import java.util.Map;
-import java.util.Set;
 import java.util.SimpleTimeZone;
 import java.util.TimeZone;
 
@@ -80,8 +73,6 @@
     private static final long ABBR_MASK = 0xf00L;
     private static final int TRANSITION_NSHIFT = 12;
 
-    private static final CalendarSystem gcal = CalendarSystem.getGregorianCalendar();
-
     /**
      * The raw GMT offset in milliseconds between this zone and GMT.
      * Negative offsets are to the west of Greenwich.  To obtain local
@@ -379,6 +370,7 @@
             throw new IllegalArgumentException();
         }
 
+        Gregorian gcal = CalendarSystem.getGregorianCalendar();
         CalendarDate date = gcal.newCalendarDate(null);
         date.setDate(year, month + 1, day);
         if (gcal.validate(date) == false) {
--- a/jdk/src/java.base/share/conf/security/java.security	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/src/java.base/share/conf/security/java.security	Mon Aug 29 08:53:32 2016 -0700
@@ -490,7 +490,7 @@
 # property is set then those two properties are ignored.
 #
 # Example,
-#   ocsp.responderCertSubjectName="CN=OCSP Responder, O=XYZ Corp"
+#   ocsp.responderCertSubjectName=CN=OCSP Responder, O=XYZ Corp
 
 #
 # Issuer name of the OCSP responder's certificate
@@ -505,7 +505,7 @@
 # property is ignored.
 #
 # Example,
-#   ocsp.responderCertIssuerName="CN=Enterprise CA, O=XYZ Corp"
+#   ocsp.responderCertIssuerName=CN=Enterprise CA, O=XYZ Corp
 
 #
 # Serial number of the OCSP responder's certificate
@@ -803,3 +803,94 @@
 #       E485B576 625E7EC6 F44C42E9 A637ED6B 0BFF5CB6 F406B7ED \
 #       EE386BFB 5A899FA5 AE9F2411 7C4B1FE6 49286651 ECE65381 \
 #       FFFFFFFF FFFFFFFF, 2}
+
+# Cryptographic Jurisdiction Policy defaults
+# 
+# Due to the import control restrictions of some countries, the default
+# JCE policy files allow for strong but "limited" cryptographic key
+# lengths to be used.  If your country's cryptographic regulations allow,
+# the "unlimited" strength policy files can be used instead, which contain
+# no restrictions on cryptographic strengths.
+# 
+# If your country has restrictions that don't fit either "limited" or
+# "unlimited", an appropriate set of policy files should be created and
+# configured before using this distribution.  The jurisdiction policy file
+# configuration must reflect the cryptographic restrictions appropriate
+# for your country.
+# 
+# YOU ARE ADVISED TO CONSULT YOUR EXPORT/IMPORT CONTROL COUNSEL OR ATTORNEY
+# TO DETERMINE THE EXACT REQUIREMENTS.
+# 
+# The policy files are flat text files organized into subdirectories of
+# <java-home>/conf/security/policy.  Each directory contains a complete
+# set of policy files.
+#
+# The "crypto.policy" Security property controls the directory selection,
+# and thus the effective cryptographic policy.
+# 
+# The default set of directories is:  
+# 
+#     limited | unlimited 
+# 
+# however other directories can be created and configured.
+# 
+# Within a directory, the effective policy is the combined minimum
+# permissions of the grant statements in the file(s) with the filename
+# pattern "default_*.policy".  At least one grant is required.  For
+# example:
+#
+#     limited   =  Export (all) + Import (limited)  =  Limited
+#     unlimited =  Export (all) + Import (all)      =  Unlimited
+#
+# The effective exemption policy is the combined minimum permissions
+# of the grant statements in the file(s) with the filename pattern
+# "exempt_*.policy".  Exemption grants are optional.
+#
+#     limited   =  grants exemption permissions, by which the
+#                  effective policy can be circumvented. 
+#                  e.g.  KeyRecovery/Escrow/Weakening.
+# 
+# Please see the JCA documentation for additional information on these
+# files and formats.
+crypto.policy=crypto.policydir-tbd
+
+#
+# The policy for the XML Signature secure validation mode. The mode is
+# enabled by setting the property "org.jcp.xml.dsig.secureValidation" to
+# true with the javax.xml.crypto.XMLCryptoContext.setProperty() method,
+# or by running the code with a SecurityManager.
+#
+#   Policy:
+#       Constraint {"," Constraint }
+#   Constraint:
+#       AlgConstraint | MaxTransformsConstraint | MaxReferencesConstraint |
+#       ReferenceUriSchemeConstraint | OtherConstraint
+#   AlgConstraint
+#       "disallowAlg" Uri
+#   MaxTransformsConstraint:
+#       "maxTransforms" Integer
+#   MaxReferencesConstraint:
+#       "maxReferences" Integer
+#   ReferenceUriSchemeConstraint:
+#       "disallowReferenceUriSchemes" String { String }
+#   OtherConstraint:
+#       "noDuplicateIds" | "noRetrievalMethodLoops"
+#
+# For AlgConstraint, Uri is the algorithm URI String that is not allowed.
+# See the XML Signature Recommendation for more information on algorithm
+# URI Identifiers. If the MaxTransformsConstraint or MaxReferencesConstraint is
+# specified more than once, only the last entry is enforced.
+#
+# Note: This property is currently used by the JDK Reference implementation. It
+# is not guaranteed to be examined and used by other implementations.
+#
+jdk.xml.dsig.secureValidationPolicy=\
+    disallowAlg http://www.w3.org/TR/1999/REC-xslt-19991116,\
+    disallowAlg http://www.w3.org/2001/04/xmldsig-more#rsa-md5,\
+    disallowAlg http://www.w3.org/2001/04/xmldsig-more#hmac-md5,\
+    disallowAlg http://www.w3.org/2001/04/xmldsig-more#md5,\
+    maxTransforms 5,\
+    maxReferences 30,\
+    disallowReferenceUriSchemes file http https,\
+    noDuplicateIds,\
+    noRetrievalMethodLoops
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/java.base/share/conf/security/policy/README.txt	Mon Aug 29 08:53:32 2016 -0700
@@ -0,0 +1,35 @@
+
+            Java(TM) Cryptography Extension Policy Files
+    for the Java(TM) Platform, Standard Edition Runtime Environment
+
+                               README
+------------------------------------------------------------------------
+
+
+The JCE architecture allows flexible cryptographic strength to be
+configured via the jurisdiction policy files contained within these
+directories.
+
+Due to import control restrictions of some countries, the default
+JCE policy files bundled in this Java Runtime Environment allow
+for strong but "limited" cryptographic strengths.  For convenience,
+this build also contains the "unlimited strength" policy files which
+contain no restrictions on cryptographic strengths, but they must be
+specifically activated by updating the "crypto.policy" Security property
+(e.g. <java-home>/conf/security/java.security) to point to the appropriate
+directory.
+
+Each subdirectory contains a complete policy configuration, and additional
+subdirectories can be added/removed to reflect local regulations.
+
+JCE for Java SE has been through the U.S. export review process.  The JCE
+framework, along with the various JCE providers that come standard with it
+(SunJCE, SunEC, SunPKCS11, SunMSCAPI, etc), is exportable from the
+United States.
+
+You are advised to consult your export/import control counsel or attorney
+to determine the exact requirements of your location, and what policy
+settings should be used.
+
+Please see The Java(TM) Cryptography Architecture (JCA) Reference
+Guide and the java.security file for more information.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/java.base/share/conf/security/policy/limited/default_US_export.policy	Mon Aug 29 08:53:32 2016 -0700
@@ -0,0 +1,6 @@
+// Default US Export policy file.
+
+grant {
+    // There is no restriction to any algorithms.
+    permission javax.crypto.CryptoAllPermission; 
+};
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/java.base/share/conf/security/policy/limited/default_local.policy	Mon Aug 29 08:53:32 2016 -0700
@@ -0,0 +1,14 @@
+// Some countries have import limits on crypto strength. This policy file
+// is worldwide importable.
+
+grant {
+    permission javax.crypto.CryptoPermission "DES", 64;
+    permission javax.crypto.CryptoPermission "DESede", *;
+    permission javax.crypto.CryptoPermission "RC2", 128, 
+                                     "javax.crypto.spec.RC2ParameterSpec", 128;
+    permission javax.crypto.CryptoPermission "RC4", 128;
+    permission javax.crypto.CryptoPermission "RC5", 128, 
+          "javax.crypto.spec.RC5ParameterSpec", *, 12, *;
+    permission javax.crypto.CryptoPermission "RSA", *;
+    permission javax.crypto.CryptoPermission *, 128;
+};
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/java.base/share/conf/security/policy/limited/exempt_local.policy	Mon Aug 29 08:53:32 2016 -0700
@@ -0,0 +1,13 @@
+// Some countries have import limits on crypto strength, but may allow for
+// these exemptions if the exemption mechanism is used.
+
+grant {
+    // There is no restriction to any algorithms if KeyRecovery is enforced.
+    permission javax.crypto.CryptoPermission *, "KeyRecovery"; 
+
+    // There is no restriction to any algorithms if KeyEscrow is enforced.
+    permission javax.crypto.CryptoPermission *, "KeyEscrow"; 
+
+    // There is no restriction to any algorithms if KeyWeakening is enforced. 
+    permission javax.crypto.CryptoPermission *, "KeyWeakening";
+};
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/java.base/share/conf/security/policy/unlimited/default_US_export.policy	Mon Aug 29 08:53:32 2016 -0700
@@ -0,0 +1,6 @@
+// Default US Export policy file.
+
+grant {
+    // There is no restriction to any algorithms.
+    permission javax.crypto.CryptoAllPermission; 
+};
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/java.base/share/conf/security/policy/unlimited/default_local.policy	Mon Aug 29 08:53:32 2016 -0700
@@ -0,0 +1,6 @@
+// Country-specific policy file for countries with no limits on crypto strength.
+
+grant {
+    // There is no restriction to any algorithms.
+    permission javax.crypto.CryptoAllPermission; 
+};
--- a/jdk/src/java.base/share/lib/security/default.policy	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/src/java.base/share/lib/security/default.policy	Mon Aug 29 08:53:32 2016 -0700
@@ -72,6 +72,8 @@
                    "removeProviderProperty.XMLDSig";
     permission java.security.SecurityPermission
                    "com.sun.org.apache.xml.internal.security.register";
+    permission java.security.SecurityPermission
+                   "getProperty.jdk.xml.dsig.secureValidationPolicy";
 };
 
 grant codeBase "jrt:/java.xml.ws" {
--- a/jdk/src/java.base/unix/classes/sun/nio/fs/UnixPath.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/src/java.base/unix/classes/sun/nio/fs/UnixPath.java	Mon Aug 29 08:53:32 2016 -0700
@@ -252,6 +252,21 @@
         return new UnixPath(getFileSystem(), new byte[0]);
     }
 
+
+    // return true if this path has "." or ".."
+    private boolean hasDotOrDotDot() {
+        int n = getNameCount();
+        for (int i=0; i<n; i++) {
+            byte[] bytes = getName(i).path;
+            if ((bytes.length == 1 && bytes[0] == '.'))
+                return true;
+            if ((bytes.length == 2 && bytes[0] == '.') && bytes[1] == '.') {
+                return true;
+            }
+        }
+        return false;
+    }
+
     @Override
     public UnixFileSystem getFileSystem() {
         return fs;
@@ -405,80 +420,94 @@
 
     @Override
     public UnixPath relativize(Path obj) {
-        UnixPath other = toUnixPath(obj);
-        if (other.equals(this))
+        UnixPath child = toUnixPath(obj);
+        if (child.equals(this))
             return emptyPath();
 
         // can only relativize paths of the same type
-        if (this.isAbsolute() != other.isAbsolute())
+        if (this.isAbsolute() != child.isAbsolute())
             throw new IllegalArgumentException("'other' is different type of Path");
 
         // this path is the empty path
         if (this.isEmpty())
-            return other;
+            return child;
 
-        int bn = this.getNameCount();
-        int cn = other.getNameCount();
+        UnixPath base = this;
+        if (base.hasDotOrDotDot() || child.hasDotOrDotDot()) {
+            base = base.normalize();
+            child = child.normalize();
+        }
+
+        int baseCount = base.getNameCount();
+        int childCount = child.getNameCount();
 
         // skip matching names
-        int n = (bn > cn) ? cn : bn;
+        int n = Math.min(baseCount, childCount);
         int i = 0;
         while (i < n) {
-            if (!this.getName(i).equals(other.getName(i)))
+            if (!base.getName(i).equals(child.getName(i)))
                 break;
             i++;
         }
 
-        int dotdots = bn - i;
-        if (i < cn) {
-            // remaining name components in other
-            UnixPath remainder = other.subpath(i, cn);
-            if (dotdots == 0)
-                return remainder;
+        // remaining elements in child
+        UnixPath childRemaining;
+        boolean isChildEmpty;
+        if (i == childCount) {
+            childRemaining = emptyPath();
+            isChildEmpty = true;
+        } else {
+            childRemaining = child.subpath(i, childCount);
+            isChildEmpty = childRemaining.isEmpty();
+        }
 
-            // other is the empty path
-            boolean isOtherEmpty = other.isEmpty();
+        // matched all of base
+        if (i == baseCount) {
+            return childRemaining;
+        }
 
-            // result is a  "../" for each remaining name in base
-            // followed by the remaining names in other. If the remainder is
-            // the empty path then we don't add the final trailing slash.
-            int len = dotdots*3 + remainder.path.length;
-            if (isOtherEmpty) {
-                assert remainder.isEmpty();
-                len--;
+        // the remainder of base cannot contain ".."
+        UnixPath baseRemaining = base.subpath(i, baseCount);
+        if (baseRemaining.hasDotOrDotDot()) {
+            throw new IllegalArgumentException("Unable to compute relative "
+                    + " path from " + this + " to " + obj);
+        }
+        if (baseRemaining.isEmpty())
+            return childRemaining;
+
+        // number of ".." needed
+        int dotdots = baseRemaining.getNameCount();
+        if (dotdots == 0) {
+            return childRemaining;
+        }
+
+        // result is a  "../" for each remaining name in base followed by the
+        // remaining names in child. If the remainder is the empty path
+        // then we don't add the final trailing slash.
+        int len = dotdots*3 + childRemaining.path.length;
+        if (isChildEmpty) {
+            assert childRemaining.isEmpty();
+            len--;
+        }
+        byte[] result = new byte[len];
+        int pos = 0;
+        while (dotdots > 0) {
+            result[pos++] = (byte)'.';
+            result[pos++] = (byte)'.';
+            if (isChildEmpty) {
+                if (dotdots > 1) result[pos++] = (byte)'/';
+            } else {
+                result[pos++] = (byte)'/';
             }
-            byte[] result = new byte[len];
-            int pos = 0;
-            while (dotdots > 0) {
-                result[pos++] = (byte)'.';
-                result[pos++] = (byte)'.';
-                if (isOtherEmpty) {
-                    if (dotdots > 1) result[pos++] = (byte)'/';
-                } else {
-                    result[pos++] = (byte)'/';
-                }
-                dotdots--;
-            }
-            System.arraycopy(remainder.path, 0, result, pos, remainder.path.length);
-            return new UnixPath(getFileSystem(), result);
-        } else {
-            // no remaining names in other so result is simply a sequence of ".."
-            byte[] result = new byte[dotdots*3 - 1];
-            int pos = 0;
-            while (dotdots > 0) {
-                result[pos++] = (byte)'.';
-                result[pos++] = (byte)'.';
-                // no tailing slash at the end
-                if (dotdots > 1)
-                    result[pos++] = (byte)'/';
-                dotdots--;
-            }
-            return new UnixPath(getFileSystem(), result);
+            dotdots--;
         }
+        System.arraycopy(childRemaining.path,0, result, pos,
+                             childRemaining.path.length);
+        return new UnixPath(getFileSystem(), result);
     }
 
     @Override
-    public Path normalize() {
+    public UnixPath normalize() {
         final int count = getNameCount();
         if (count == 0 || isEmpty())
             return this;
--- a/jdk/src/java.base/windows/classes/sun/nio/fs/WindowsPath.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/src/java.base/windows/classes/sun/nio/fs/WindowsPath.java	Mon Aug 29 08:53:32 2016 -0700
@@ -375,57 +375,108 @@
         return (WindowsPath)path;
     }
 
+    // return true if this path has "." or ".."
+    private boolean hasDotOrDotDot() {
+        int n = getNameCount();
+        for (int i=0; i<n; i++) {
+            String name = elementAsString(i);
+            if (name.length() == 1 && name.charAt(0) == '.')
+                return true;
+            if (name.length() == 2
+                    && name.charAt(0) == '.' && name.charAt(1) == '.')
+                return true;
+        }
+        return false;
+    }
+
     @Override
     public WindowsPath relativize(Path obj) {
-        WindowsPath other = toWindowsPath(obj);
-        if (this.equals(other))
+        WindowsPath child = toWindowsPath(obj);
+        if (this.equals(child))
             return emptyPath();
 
         // can only relativize paths of the same type
-        if (this.type != other.type)
+        if (this.type != child.type)
             throw new IllegalArgumentException("'other' is different type of Path");
 
         // can only relativize paths if root component matches
-        if (!this.root.equalsIgnoreCase(other.root))
+        if (!this.root.equalsIgnoreCase(child.root))
             throw new IllegalArgumentException("'other' has different root");
 
         // this path is the empty path
         if (this.isEmpty())
-            return other;
+            return child;
 
-        int bn = this.getNameCount();
-        int cn = other.getNameCount();
+
+        WindowsPath base = this;
+        if (base.hasDotOrDotDot() || child.hasDotOrDotDot()) {
+            base = base.normalize();
+            child = child.normalize();
+        }
+
+        int baseCount = base.getNameCount();
+        int childCount = child.getNameCount();
 
         // skip matching names
-        int n = (bn > cn) ? cn : bn;
+        int n = Math.min(baseCount, childCount);
         int i = 0;
         while (i < n) {
-            if (!this.getName(i).equals(other.getName(i)))
+            if (!base.getName(i).equals(child.getName(i)))
                 break;
             i++;
         }
 
-        // append ..\ for remaining names in the base
+        // remaining elements in child
+        WindowsPath childRemaining;
+        boolean isChildEmpty;
+        if (i == childCount) {
+            childRemaining = emptyPath();
+            isChildEmpty = true;
+        } else {
+            childRemaining = child.subpath(i, childCount);
+            isChildEmpty = childRemaining.isEmpty();
+        }
+
+        // matched all of base
+        if (i == baseCount) {
+            return childRemaining;
+        }
+
+        // the remainder of base cannot contain ".."
+        WindowsPath baseRemaining = base.subpath(i, baseCount);
+        if (baseRemaining.hasDotOrDotDot()) {
+            throw new IllegalArgumentException("Unable to compute relative "
+                    + " path from " + this + " to " + obj);
+        }
+        if (baseRemaining.isEmpty())
+            return childRemaining;
+
+        // number of ".." needed
+        int dotdots = baseRemaining.getNameCount();
+        if (dotdots == 0) {
+            return childRemaining;
+        }
+
         StringBuilder result = new StringBuilder();
-        for (int j=i; j<bn; j++) {
+        for (int j=0; j<dotdots; j++) {
             result.append("..\\");
         }
 
         // append remaining names in child
-        if (!other.isEmpty()) {
-            for (int j=i; j<cn; j++) {
-                result.append(other.getName(j).toString());
+        if (!isChildEmpty) {
+            for (int j=0; j<childRemaining.getNameCount(); j++) {
+                result.append(childRemaining.getName(j).toString());
                 result.append("\\");
             }
         }
 
-        // drop trailing slash in result
+        // drop trailing slash
         result.setLength(result.length()-1);
         return createFromNormalizedPath(getFileSystem(), result.toString());
     }
 
     @Override
-    public Path normalize() {
+    public WindowsPath normalize() {
         final int count = getNameCount();
         if (count == 0 || isEmpty())
             return this;
--- a/jdk/src/java.security.jgss/share/classes/sun/security/krb5/KdcComm.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/src/java.security.jgss/share/classes/sun/security/krb5/KdcComm.java	Mon Aug 29 08:53:32 2016 -0700
@@ -390,35 +390,27 @@
 
             for (int i=1; i <= retries; i++) {
                 String proto = useTCP?"TCP":"UDP";
-                try (NetClient kdcClient = NetClient.getInstance(
-                        proto, kdc, port, timeout)) {
-                    if (DEBUG) {
-                        System.out.println(">>> KDCCommunication: kdc=" + kdc
+                if (DEBUG) {
+                    System.out.println(">>> KDCCommunication: kdc=" + kdc
                             + " " + proto + ":"
                             +  port +  ", timeout="
                             + timeout
                             + ",Attempt =" + i
                             + ", #bytes=" + obuf.length);
+                }
+                try (NetClient kdcClient = NetClient.getInstance(
+                        proto, kdc, port, timeout)) {
+                    kdcClient.send(obuf);
+                    ibuf = kdcClient.receive();
+                    break;
+                } catch (SocketTimeoutException se) {
+                    if (DEBUG) {
+                        System.out.println ("SocketTimeOutException with " +
+                                "attempt: " + i);
                     }
-                    try {
-                        /*
-                        * Send the data to the kdc.
-                        */
-                        kdcClient.send(obuf);
-                        /*
-                        * And get a response.
-                        */
-                        ibuf = kdcClient.receive();
-                        break;
-                    } catch (SocketTimeoutException se) {
-                        if (DEBUG) {
-                            System.out.println ("SocketTimeOutException with " +
-                                                "attempt: " + i);
-                        }
-                        if (i == retries) {
-                            ibuf = null;
-                            throw se;
-                        }
+                    if (i == retries) {
+                        ibuf = null;
+                        throw se;
                     }
                 }
             }
--- a/jdk/src/java.sql.rowset/share/classes/javax/sql/rowset/BaseRowSet.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/src/java.sql.rowset/share/classes/javax/sql/rowset/BaseRowSet.java	Mon Aug 29 08:53:32 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 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
@@ -3204,7 +3204,6 @@
     * this method is called on a closed <code>CallableStatement</code>
     * @exception SQLFeatureNotSupportedException if the JDBC driver does not support
     * this method
-    * @since 1.4
     */
    public void setNull(String parameterName, int sqlType) throws SQLException {
         throw new SQLFeatureNotSupportedException("Feature not supported");
@@ -3240,7 +3239,6 @@
     * this method is called on a closed <code>CallableStatement</code>
     * @exception SQLFeatureNotSupportedException if the JDBC driver does not support
     * this method
-    * @since 1.4
     */
    public void setNull (String parameterName, int sqlType, String typeName)
        throws SQLException{
@@ -3259,7 +3257,6 @@
     * @exception SQLFeatureNotSupportedException if the JDBC driver does not support
     * this method
     * @see #getParams
-    * @since 1.4
     */
    public void setBoolean(String parameterName, boolean x) throws SQLException{
         throw new SQLFeatureNotSupportedException("Feature not supported");
@@ -3277,7 +3274,6 @@
     * @exception SQLFeatureNotSupportedException if the JDBC driver does not support
     * this method
     * @see #getParams
-    * @since 1.4
     */
    public void setByte(String parameterName, byte x) throws SQLException{
         throw new SQLFeatureNotSupportedException("Feature not supported");
@@ -3295,7 +3291,6 @@
     * @exception SQLFeatureNotSupportedException if the JDBC driver does not support
     * this method
     * @see #getParams
-    * @since 1.4
     */
    public void setShort(String parameterName, short x) throws SQLException{
         throw new SQLFeatureNotSupportedException("Feature not supported");
@@ -3313,7 +3308,6 @@
     * @exception SQLFeatureNotSupportedException if the JDBC driver does not support
     * this method
     * @see #getParams
-    * @since 1.4
     */
    public void setInt(String parameterName, int x) throws SQLException{
         throw new SQLFeatureNotSupportedException("Feature not supported");
@@ -3332,7 +3326,6 @@
     * @exception SQLFeatureNotSupportedException if the JDBC driver does not support
     * this method
     * @see #getParams
-    * @since 1.4
     */
    public void setLong(String parameterName, long x) throws SQLException{
         throw new SQLFeatureNotSupportedException("Feature not supported");
@@ -3350,7 +3343,6 @@
     * @exception SQLFeatureNotSupportedException if the JDBC driver does not support
     * this method
     * @see #getParams
-    * @since 1.4
     */
    public void setFloat(String parameterName, float x) throws SQLException{
         throw new SQLFeatureNotSupportedException("Feature not supported");
@@ -3368,7 +3360,6 @@
     * @exception SQLFeatureNotSupportedException if the JDBC driver does not support
     * this method
     * @see #getParams
-    * @since 1.4
     */
    public void setDouble(String parameterName, double x) throws SQLException{
         throw new SQLFeatureNotSupportedException("Feature not supported");
@@ -3387,7 +3378,6 @@
     * @exception SQLFeatureNotSupportedException if the JDBC driver does not support
     * this method
     * @see #getParams
-    * @since 1.4
     */
    public void setBigDecimal(String parameterName, BigDecimal x) throws SQLException{
         throw new SQLFeatureNotSupportedException("Feature not supported");
@@ -3408,7 +3398,6 @@
     * @exception SQLFeatureNotSupportedException if the JDBC driver does not support
     * this method
     * @see #getParams
-    * @since 1.4
     */
    public void setString(String parameterName, String x) throws SQLException{
         throw new SQLFeatureNotSupportedException("Feature not supported");
@@ -3428,7 +3417,6 @@
     * @exception SQLFeatureNotSupportedException if the JDBC driver does not support
     * this method
     * @see #getParams
-    * @since 1.4
     */
    public void setBytes(String parameterName, byte x[]) throws SQLException{
         throw new SQLFeatureNotSupportedException("Feature not supported");
@@ -3447,7 +3435,6 @@
     * @exception SQLFeatureNotSupportedException if the JDBC driver does not support
     * this method
     * @see #getParams
-    * @since 1.4
     */
    public void setTimestamp(String parameterName, java.sql.Timestamp x)
        throws SQLException{
@@ -3474,7 +3461,6 @@
     * this method is called on a closed <code>CallableStatement</code>
     * @exception SQLFeatureNotSupportedException if the JDBC driver does not support
     * this method
-    * @since 1.4
     */
    public void setAsciiStream(String parameterName, java.io.InputStream x, int length)
        throws SQLException{
@@ -3500,7 +3486,6 @@
     * this method is called on a closed <code>CallableStatement</code>
     * @exception SQLFeatureNotSupportedException if the JDBC driver does not support
     * this method
-    * @since 1.4
     */
    public void setBinaryStream(String parameterName, java.io.InputStream x,
                         int length) throws SQLException{
@@ -3528,7 +3513,6 @@
     * this method is called on a closed <code>CallableStatement</code>
     * @exception SQLFeatureNotSupportedException if the JDBC driver does not support
     * this method
-    * @since 1.4
     */
    public void setCharacterStream(String parameterName,
                            java.io.Reader reader,
@@ -3684,7 +3668,6 @@
     * this data type
     * @see Types
     * @see #getParams
-    * @since 1.4
     */
    public void setObject(String parameterName, Object x, int targetSqlType, int scale)
        throws SQLException{
@@ -3710,7 +3693,6 @@
     * or  <code>STRUCT</code> data type and the JDBC driver does not support
     * this data type
     * @see #getParams
-    * @since 1.4
     */
    public void setObject(String parameterName, Object x, int targetSqlType)
        throws SQLException{
@@ -3751,7 +3733,6 @@
    * @exception SQLFeatureNotSupportedException if the JDBC driver does not support
    * this method
    * @see #getParams
-   * @since 1.4
    */
   public void setObject(String parameterName, Object x) throws SQLException{
         throw new SQLFeatureNotSupportedException("Feature not supported");
@@ -4024,7 +4005,6 @@
     * @exception SQLFeatureNotSupportedException if the JDBC driver does not support
     * this method
     * @see #getParams
-    * @since 1.4
     */
    public void setDate(String parameterName, java.sql.Date x)
            throws SQLException {
@@ -4050,7 +4030,6 @@
     * @exception SQLFeatureNotSupportedException if the JDBC driver does not support
     * this method
     * @see #getParams
-    * @since 1.4
     */
    public void setDate(String parameterName, java.sql.Date x, Calendar cal)
            throws SQLException {
@@ -4069,7 +4048,6 @@
     * @exception SQLFeatureNotSupportedException if the JDBC driver does not support
     * this method
     * @see #getParams
-    * @since 1.4
     */
    public void setTime(String parameterName, java.sql.Time x)
            throws SQLException {
@@ -4095,7 +4073,6 @@
     * @exception SQLFeatureNotSupportedException if the JDBC driver does not support
     * this method
     * @see #getParams
-    * @since 1.4
     */
    public void setTime(String parameterName, java.sql.Time x, Calendar cal)
            throws SQLException {
@@ -4121,7 +4098,6 @@
     * @exception SQLFeatureNotSupportedException if the JDBC driver does not support
     * this method
     * @see #getParams
-    * @since 1.4
     */
    public void setTimestamp(String parameterName, java.sql.Timestamp x, Calendar cal)
            throws SQLException {
@@ -4459,7 +4435,6 @@
     * @exception SQLException if a database access error occurs or
     * this method is called on a closed <code>PreparedStatement</code>
     * @throws SQLFeatureNotSupportedException  if the JDBC driver does not support this method
-    * @since 1.4
     */
    public void setURL(int parameterIndex, java.net.URL x) throws SQLException {
        throw new SQLFeatureNotSupportedException("Feature not supported");
--- a/jdk/src/java.sql/share/classes/javax/sql/CommonDataSource.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/src/java.sql/share/classes/javax/sql/CommonDataSource.java	Mon Aug 29 08:53:32 2016 -0700
@@ -57,7 +57,6 @@
      *        logging is disabled
      * @exception java.sql.SQLException if a database access error occurs
      * @see #setLogWriter
-     * @since 1.4
      */
     java.io.PrintWriter getLogWriter() throws SQLException;
 
@@ -79,7 +78,6 @@
      * @param out the new log writer; to disable logging, set to null
      * @exception SQLException if a database access error occurs
      * @see #getLogWriter
-     * @since 1.4
      */
     void setLogWriter(java.io.PrintWriter out) throws SQLException;
 
@@ -94,7 +92,6 @@
      * @param seconds the data source login time limit
      * @exception SQLException if a database access error occurs.
      * @see #getLoginTimeout
-     * @since 1.4
      */
     void setLoginTimeout(int seconds) throws SQLException;
 
@@ -109,7 +106,6 @@
      * @return the data source login time limit
      * @exception SQLException if a database access error occurs.
      * @see #setLoginTimeout
-     * @since 1.4
      */
     int getLoginTimeout() throws SQLException;
 
--- a/jdk/src/java.sql/share/classes/javax/sql/ConnectionPoolDataSource.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/src/java.sql/share/classes/javax/sql/ConnectionPoolDataSource.java	Mon Aug 29 08:53:32 2016 -0700
@@ -72,6 +72,34 @@
   PooledConnection getPooledConnection(String user, String password)
     throws SQLException;
 
+  /**
+   * {@inheritDoc}
+   * @since 1.4
+   */
+  @Override
+  java.io.PrintWriter getLogWriter() throws SQLException;
+
+  /**
+   * {@inheritDoc}
+   * @since 1.4
+   */
+  @Override
+  void setLogWriter(java.io.PrintWriter out) throws SQLException;
+
+  /**
+   * {@inheritDoc}
+   * @since 1.4
+   */
+  @Override
+  void setLoginTimeout(int seconds) throws SQLException;
+
+  /**
+   * {@inheritDoc}
+   * @since 1.4
+   */
+  @Override
+  int getLoginTimeout() throws SQLException;
+
   //------------------------- JDBC 4.3 -----------------------------------
 
   /**
--- a/jdk/src/java.sql/share/classes/javax/sql/DataSource.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/src/java.sql/share/classes/javax/sql/DataSource.java	Mon Aug 29 08:53:32 2016 -0700
@@ -109,6 +109,34 @@
   Connection getConnection(String username, String password)
     throws SQLException;
 
+  /**
+   * {@inheritDoc}
+   * @since 1.4
+   */
+  @Override
+  java.io.PrintWriter getLogWriter() throws SQLException;
+
+  /**
+   * {@inheritDoc}
+   * @since 1.4
+   */
+  @Override
+  void setLogWriter(java.io.PrintWriter out) throws SQLException;
+
+  /**
+   * {@inheritDoc}
+   * @since 1.4
+   */
+  @Override
+  void setLoginTimeout(int seconds) throws SQLException;
+
+  /**
+   * {@inheritDoc}
+   * @since 1.4
+   */
+  @Override
+  int getLoginTimeout() throws SQLException;
+
   // JDBC 4.3
 
   /**
--- a/jdk/src/java.sql/share/classes/javax/sql/XADataSource.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/src/java.sql/share/classes/javax/sql/XADataSource.java	Mon Aug 29 08:53:32 2016 -0700
@@ -81,7 +81,35 @@
   XAConnection getXAConnection(String user, String password)
     throws SQLException;
 
-  // JDBC 4.3
+  /**
+   * {@inheritDoc}
+   * @since 1.4
+   */
+  @Override
+  java.io.PrintWriter getLogWriter() throws SQLException;
+
+  /**
+   * {@inheritDoc}
+   * @since 1.4
+   */
+  @Override
+  void setLogWriter(java.io.PrintWriter out) throws SQLException;
+
+  /**
+   * {@inheritDoc}
+   * @since 1.4
+   */
+  @Override
+  void setLoginTimeout(int seconds) throws SQLException;
+
+  /**
+   * {@inheritDoc}
+   * @since 1.4
+   */
+  @Override
+  int getLoginTimeout() throws SQLException;
+
+   // JDBC 4.3
 
   /**
    * Creates a new {@code XAConnectionBuilder} instance
--- a/jdk/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/IntegrityHmac.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/IntegrityHmac.java	Mon Aug 29 08:53:32 2016 -0700
@@ -150,7 +150,7 @@
             this.macAlgorithm.init(secretKey);
         } catch (InvalidKeyException ex) {
             // reinstantiate Mac object to work around bug in JDK
-            // see: http://bugs.sun.com/view_bug.do?bug_id=4953555
+            // see: http://bugs.java.com/view_bug.do?bug_id=4953555
             Mac mac = this.macAlgorithm;
             try {
                 this.macAlgorithm = Mac.getInstance(macAlgorithm.getAlgorithm());
--- a/jdk/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureBaseRSA.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureBaseRSA.java	Mon Aug 29 08:53:32 2016 -0700
@@ -112,7 +112,7 @@
             this.signatureAlgorithm.initVerify((PublicKey) publicKey);
         } catch (InvalidKeyException ex) {
             // reinstantiate Signature object to work around bug in JDK
-            // see: http://bugs.sun.com/view_bug.do?bug_id=4953555
+            // see: http://bugs.java.com/view_bug.do?bug_id=4953555
             Signature sig = this.signatureAlgorithm;
             try {
                 this.signatureAlgorithm = Signature.getInstance(signatureAlgorithm.getAlgorithm());
--- a/jdk/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureDSA.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureDSA.java	Mon Aug 29 08:53:32 2016 -0700
@@ -139,7 +139,7 @@
             this.signatureAlgorithm.initVerify((PublicKey) publicKey);
         } catch (InvalidKeyException ex) {
             // reinstantiate Signature object to work around bug in JDK
-            // see: http://bugs.sun.com/view_bug.do?bug_id=4953555
+            // see: http://bugs.java.com/view_bug.do?bug_id=4953555
             Signature sig = this.signatureAlgorithm;
             try {
                 this.signatureAlgorithm = Signature.getInstance(signatureAlgorithm.getAlgorithm());
--- a/jdk/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureECDSA.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureECDSA.java	Mon Aug 29 08:53:32 2016 -0700
@@ -252,7 +252,7 @@
             this.signatureAlgorithm.initVerify((PublicKey) publicKey);
         } catch (InvalidKeyException ex) {
             // reinstantiate Signature object to work around bug in JDK
-            // see: http://bugs.sun.com/view_bug.do?bug_id=4953555
+            // see: http://bugs.java.com/view_bug.do?bug_id=4953555
             Signature sig = this.signatureAlgorithm;
             try {
                 this.signatureAlgorithm = Signature.getInstance(signatureAlgorithm.getAlgorithm());
--- a/jdk/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/ApacheTransform.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/ApacheTransform.java	Mon Aug 29 08:53:32 2016 -0700
@@ -21,7 +21,7 @@
  * under the License.
  */
 /*
- * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * $Id: ApacheTransform.java 1333869 2012-05-04 10:42:44Z coheigea $
@@ -38,7 +38,6 @@
 
 import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput;
 import com.sun.org.apache.xml.internal.security.transforms.Transform;
-import com.sun.org.apache.xml.internal.security.transforms.Transforms;
 
 import javax.xml.crypto.*;
 import javax.xml.crypto.dom.DOMCryptoContext;
@@ -150,7 +149,7 @@
 
         if (Utils.secureValidation(xc)) {
             String algorithm = getAlgorithm();
-            if (Transforms.TRANSFORM_XSLT.equals(algorithm)) {
+            if (Policy.restrictAlg(algorithm)) {
                 throw new TransformException(
                     "Transform " + algorithm + " is forbidden when secure validation is enabled"
                 );
--- a/jdk/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMManifest.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMManifest.java	Mon Aug 29 08:53:32 2016 -0700
@@ -21,7 +21,7 @@
  * under the License.
  */
 /*
- * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * $Id: DOMManifest.java 1333415 2012-05-03 12:03:51Z coheigea $
@@ -110,9 +110,10 @@
                                            localName + ", expected Reference");
             }
             refs.add(new DOMReference(refElem, context, provider));
-            if (secVal && (refs.size() > DOMSignedInfo.MAXIMUM_REFERENCE_COUNT)) {
-                String error = "A maxiumum of " + DOMSignedInfo.MAXIMUM_REFERENCE_COUNT + " "
-                    + "references per Manifest are allowed with secure validation";
+            if (secVal && Policy.restrictNumReferences(refs.size())) {
+                String error = "A maximum of " + Policy.maxReferences()
+                    + " references per Manifest are allowed when"
+                    + " secure validation is enabled";
                 throw new MarshalException(error);
             }
             refElem = DOMUtils.getNextSiblingElement(refElem);
--- a/jdk/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMReference.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMReference.java	Mon Aug 29 08:53:32 2016 -0700
@@ -21,7 +21,7 @@
  * under the License.
  */
 /*
- * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * ===========================================================================
@@ -51,7 +51,6 @@
 import org.w3c.dom.Node;
 
 import org.jcp.xml.dsig.internal.DigesterOutputStream;
-import com.sun.org.apache.xml.internal.security.algorithms.MessageDigestAlgorithm;
 import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;
 import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput;
 import com.sun.org.apache.xml.internal.security.utils.Base64;
@@ -67,11 +66,6 @@
     implements Reference, DOMURIReference {
 
    /**
-    * The maximum number of transforms per reference, if secure validation is enabled.
-    */
-   public static final int MAXIMUM_TRANSFORM_COUNT = 5;
-
-   /**
     * Look up useC14N11 system property. If true, an explicit C14N11 transform
     * will be added if necessary when generating the signature. See section
     * 3.1.1 of http://www.w3.org/2007/xmlsec/Drafts/xmldsig-core/ for more info.
@@ -208,9 +202,10 @@
                 }
                 transforms.add
                     (new DOMTransform(transformElem, context, provider));
-                if (secVal && (transforms.size() > MAXIMUM_TRANSFORM_COUNT)) {
-                    String error = "A maxiumum of " + MAXIMUM_TRANSFORM_COUNT + " "
-                        + "transforms per Reference are allowed with secure validation";
+                if (secVal && Policy.restrictNumTransforms(transforms.size())) {
+                    String error = "A maximum of " + Policy.maxTransforms()
+                        + " transforms per Reference are allowed when"
+                        + " secure validation is enabled";
                     throw new MarshalException(error);
                 }
                 transformElem = DOMUtils.getNextSiblingElement(transformElem);
@@ -227,10 +222,10 @@
         Element dmElem = nextSibling;
         this.digestMethod = DOMDigestMethod.unmarshal(dmElem);
         String digestMethodAlgorithm = this.digestMethod.getAlgorithm();
-        if (secVal
-            && MessageDigestAlgorithm.ALGO_ID_DIGEST_NOT_RECOMMENDED_MD5.equals(digestMethodAlgorithm)) {
+        if (secVal && Policy.restrictAlg(digestMethodAlgorithm)) {
             throw new MarshalException(
-                "It is forbidden to use algorithm " + digestMethod + " when secure validation is enabled"
+                "It is forbidden to use algorithm " + digestMethodAlgorithm +
+                " when secure validation is enabled"
             );
         }
 
--- a/jdk/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMRetrievalMethod.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMRetrievalMethod.java	Mon Aug 29 08:53:32 2016 -0700
@@ -21,7 +21,7 @@
  * under the License.
  */
 /*
- * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * ===========================================================================
@@ -149,9 +149,10 @@
                 }
                 transforms.add
                     (new DOMTransform(transformElem, context, provider));
-                if (secVal && (transforms.size() > DOMReference.MAXIMUM_TRANSFORM_COUNT)) {
-                    String error = "A maxiumum of " + DOMReference.MAXIMUM_TRANSFORM_COUNT + " "
-                        + "transforms per Reference are allowed with secure validation";
+                if (secVal && Policy.restrictNumTransforms(transforms.size())) {
+                    String error = "A maximum of " + Policy.maxTransforms()
+                        + " transforms per Reference are allowed when"
+                        + " secure validation is enabled";
                     throw new MarshalException(error);
                 }
                 transformElem = DOMUtils.getNextSiblingElement(transformElem);
@@ -238,7 +239,8 @@
         }
 
         // guard against RetrievalMethod loops
-        if ((data instanceof NodeSetData) && Utils.secureValidation(context)) {
+        if ((data instanceof NodeSetData) && Utils.secureValidation(context)
+            && Policy.restrictRetrievalMethodLoops()) {
             NodeSetData<?> nsd = (NodeSetData<?>)data;
             Iterator<?> i = nsd.iterator();
             if (i.hasNext()) {
--- a/jdk/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignedInfo.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignedInfo.java	Mon Aug 29 08:53:32 2016 -0700
@@ -21,7 +21,7 @@
  * under the License.
  */
 /*
- * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * $Id: DOMSignedInfo.java 1333415 2012-05-03 12:03:51Z coheigea $
@@ -45,7 +45,6 @@
 import org.w3c.dom.Node;
 
 import com.sun.org.apache.xml.internal.security.utils.Base64;
-import com.sun.org.apache.xml.internal.security.utils.Constants;
 import com.sun.org.apache.xml.internal.security.utils.UnsyncBufferedOutputStream;
 
 /**
@@ -55,22 +54,9 @@
  */
 public final class DOMSignedInfo extends DOMStructure implements SignedInfo {
 
-    /**
-     * The maximum number of references per Manifest, if secure validation is enabled.
-     */
-    public static final int MAXIMUM_REFERENCE_COUNT = 30;
-
     private static java.util.logging.Logger log =
         java.util.logging.Logger.getLogger("org.jcp.xml.dsig.internal.dom");
 
-    /** Signature - NOT Recommended RSAwithMD5 */
-    private static final String ALGO_ID_SIGNATURE_NOT_RECOMMENDED_RSA_MD5 =
-        Constants.MoreAlgorithmsSpecNS + "rsa-md5";
-
-    /** HMAC - NOT Recommended HMAC-MD5 */
-    private static final String ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5 =
-        Constants.MoreAlgorithmsSpecNS + "hmac-md5";
-
     private List<Reference> references;
     private CanonicalizationMethod canonicalizationMethod;
     private SignatureMethod signatureMethod;
@@ -158,10 +144,10 @@
         boolean secVal = Utils.secureValidation(context);
 
         String signatureMethodAlgorithm = signatureMethod.getAlgorithm();
-        if (secVal && ((ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5.equals(signatureMethodAlgorithm)
-                || ALGO_ID_SIGNATURE_NOT_RECOMMENDED_RSA_MD5.equals(signatureMethodAlgorithm)))) {
+        if (secVal && Policy.restrictAlg(signatureMethodAlgorithm)) {
             throw new MarshalException(
-                "It is forbidden to use algorithm " + signatureMethod + " when secure validation is enabled"
+                "It is forbidden to use algorithm " + signatureMethodAlgorithm +
+                " when secure validation is enabled"
             );
         }
 
@@ -179,9 +165,10 @@
             }
             refList.add(new DOMReference(refElem, context, provider));
 
-            if (secVal && (refList.size() > MAXIMUM_REFERENCE_COUNT)) {
-                String error = "A maxiumum of " + MAXIMUM_REFERENCE_COUNT + " "
-                    + "references per Manifest are allowed with secure validation";
+            if (secVal && Policy.restrictNumReferences(refList.size())) {
+                String error = "A maximum of " + Policy.maxReferences()
+                    + " references per Manifest are allowed when"
+                    + " secure validation is enabled";
                 throw new MarshalException(error);
             }
             refElem = DOMUtils.getNextSiblingElement(refElem);
--- a/jdk/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMURIDereferencer.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMURIDereferencer.java	Mon Aug 29 08:53:32 2016 -0700
@@ -21,7 +21,7 @@
  * under the License.
  */
 /*
- * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * $Id: DOMURIDereferencer.java 1231033 2012-01-13 12:12:12Z coheigea $
@@ -73,6 +73,11 @@
 
         boolean secVal = Utils.secureValidation(context);
 
+        if (secVal && Policy.restrictReferenceUriScheme(uri)) {
+            throw new URIReferenceException(
+                "Uri " + uri + " is forbidden when secure validation is enabled");
+        }
+
         // Check if same-document URI and already registered on the context
         if (uri != null && uri.length() != 0 && uri.charAt(0) == '#') {
             String id = uri.substring(1);
@@ -83,12 +88,19 @@
                 id = id.substring(i1+1, i2);
             }
 
-            Node referencedElem = dcc.getElementById(id);
+            // check if element is registered by Id
+            Node referencedElem = uriAttr.getOwnerDocument().getElementById(id);
+            if (referencedElem == null) {
+               // see if element is registered in DOMCryptoContext
+               referencedElem = dcc.getElementById(id);
+            }
             if (referencedElem != null) {
-                if (secVal) {
+                if (secVal && Policy.restrictDuplicateIds()) {
                     Element start = referencedElem.getOwnerDocument().getDocumentElement();
                     if (!XMLUtils.protectAgainstWrappingAttack(start, (Element)referencedElem, id)) {
-                        String error = "Multiple Elements with the same ID " + id + " were detected";
+                        String error = "Multiple Elements with the same ID "
+                            + id + " detected when secure validation"
+                            + " is enabled";
                         throw new URIReferenceException(error);
                     }
                 }
@@ -110,9 +122,9 @@
 
         try {
             ResourceResolver apacheResolver =
-                ResourceResolver.getInstance(uriAttr, baseURI, secVal);
+                ResourceResolver.getInstance(uriAttr, baseURI, false);
             XMLSignatureInput in = apacheResolver.resolve(uriAttr,
-                                                          baseURI, secVal);
+                                                          baseURI, false);
             if (in.isOctetStream()) {
                 return new ApacheOctetStreamData(in);
             } else {
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/Policy.java	Mon Aug 29 08:53:32 2016 -0700
@@ -0,0 +1,178 @@
+/*
+ * 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 org.jcp.xml.dsig.internal.dom;
+
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.security.AccessController;
+import java.security.AccessController;
+import java.security.PrivilegedAction;
+import java.security.Security;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Locale;
+import java.util.Set;
+
+/**
+ * The secure validation policy as specified by the
+ * jdk.xml.dsig.secureValidationPolicy security property.
+ */
+public final class Policy {
+
+    // all restrictions are initialized to be unconstrained
+    private static Set<URI> disallowedAlgs = new HashSet<>();
+    private static int maxTrans = Integer.MAX_VALUE;
+    private static int maxRefs = Integer.MAX_VALUE;
+    private static Set<String> disallowedRefUriSchemes = new HashSet<>();
+    private static boolean noDuplicateIds = false;
+    private static boolean noRMLoops = false;
+
+    static {
+        try {
+            initialize();
+        } catch (Exception e) {
+            throw new SecurityException(
+                "Cannot initialize the secure validation policy", e);
+        }
+    }
+
+    private Policy() {}
+
+    private static void initialize() {
+        String prop =
+            AccessController.doPrivileged((PrivilegedAction<String>) () ->
+                Security.getProperty("jdk.xml.dsig.secureValidationPolicy"));
+        if (prop == null || prop.isEmpty()) {
+            // no policy specified, so don't enforce any restrictions
+            return;
+        }
+        String[] entries = prop.split(",");
+        for (String entry : entries) {
+            String[] tokens = entry.split("\\s");
+            String type = tokens[0];
+            switch(type) {
+                case "disallowAlg":
+                    if (tokens.length != 2) {
+                        error(entry);
+                    }
+                    disallowedAlgs.add(URI.create(tokens[1]));
+                    break;
+                case "maxTransforms":
+                    if (tokens.length != 2) {
+                        error(entry);
+                    }
+                    maxTrans = Integer.parseUnsignedInt(tokens[1]);
+                    break;
+                case "maxReferences":
+                    if (tokens.length != 2) {
+                        error(entry);
+                    }
+                    maxRefs = Integer.parseUnsignedInt(tokens[1]);
+                    break;
+                case "disallowReferenceUriSchemes":
+                    if (tokens.length == 1) {
+                        error(entry);
+                    }
+                    for (int i = 1; i < tokens.length; i++) {
+                        String scheme = tokens[i];
+                        disallowedRefUriSchemes.add(
+                            scheme.toLowerCase(Locale.ROOT));
+                    }
+                    break;
+                case "noDuplicateIds":
+                    if (tokens.length != 1) {
+                        error(entry);
+                    }
+                    noDuplicateIds = true;
+                    break;
+                case "noRetrievalMethodLoops":
+                    if (tokens.length != 1) {
+                        error(entry);
+                    }
+                    noRMLoops = true;
+                    break;
+                default:
+                    error(entry);
+            }
+        }
+    }
+
+    public static boolean restrictAlg(String alg) {
+        try {
+            URI uri = new URI(alg);
+            return disallowedAlgs.contains(uri);
+        } catch (URISyntaxException use) {
+            return false;
+        }
+    }
+
+    public static boolean restrictNumTransforms(int numTrans) {
+        return (numTrans > maxTrans);
+    }
+
+    public static boolean restrictNumReferences(int numRefs) {
+        return (numRefs > maxRefs);
+    }
+
+    public static boolean restrictReferenceUriScheme(String uri) {
+        if (uri != null) {
+            String scheme = java.net.URI.create(uri).getScheme();
+            if (scheme != null) {
+                return disallowedRefUriSchemes.contains(
+                    scheme.toLowerCase(Locale.ROOT));
+            }
+        }
+        return false;
+    }
+
+    public static boolean restrictDuplicateIds() {
+        return noDuplicateIds;
+    }
+
+    public static boolean restrictRetrievalMethodLoops() {
+        return noRMLoops;
+    }
+
+    public static Set<URI> disabledAlgs() {
+        return Collections.<URI>unmodifiableSet(disallowedAlgs);
+    }
+
+    public static int maxTransforms() {
+        return maxTrans;
+    }
+
+    public static int maxReferences() {
+        return maxRefs;
+    }
+
+    public static Set<String> disabledReferenceUriSchemes() {
+        return Collections.<String>unmodifiableSet(disallowedRefUriSchemes);
+    }
+
+    private static void error(String entry) {
+        throw new IllegalArgumentException(
+            "Invalid jdk.xml.dsig.secureValidationPolicy entry: " + entry);
+    }
+}
--- a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/P11RSACipher.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/P11RSACipher.java	Mon Aug 29 08:53:32 2016 -0700
@@ -358,7 +358,9 @@
                 System.arraycopy(buffer, 0, tmpBuffer, 0, bufOfs);
                 tmpBuffer = p11.C_Sign(session.id(), tmpBuffer);
                 if (tmpBuffer.length > outLen) {
-                    throw new BadPaddingException("Output buffer too small");
+                    throw new BadPaddingException(
+                        "Output buffer (" + outLen + ") is too small to " +
+                        "hold the produced data (" + tmpBuffer.length + ")");
                 }
                 System.arraycopy(tmpBuffer, 0, out, outOfs, tmpBuffer.length);
                 n = tmpBuffer.length;
--- a/jdk/src/jdk.crypto.pkcs11/share/native/libj2pkcs11/p11_util.c	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/src/jdk.crypto.pkcs11/share/native/libj2pkcs11/p11_util.c	Mon Aug 29 08:53:32 2016 -0700
@@ -558,7 +558,7 @@
     pCharArray = (*env)->GetStringUTFChars(env, jArray, &isCopy);
     if (pCharArray == NULL) { return; }
 
-    *ckpLength = strlen(pCharArray);
+    *ckpLength = (CK_ULONG) strlen(pCharArray);
     *ckpArray = (CK_UTF8CHAR_PTR) malloc((*ckpLength + 1) * sizeof(CK_UTF8CHAR));
     if (*ckpArray == NULL) {
         (*env)->ReleaseStringUTFChars(env, (jstring) jArray, pCharArray);
--- a/jdk/src/jdk.crypto.pkcs11/unix/native/libj2pkcs11/j2secmod_md.c	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/src/jdk.crypto.pkcs11/unix/native/libj2pkcs11/j2secmod_md.c	Mon Aug 29 08:53:32 2016 -0700
@@ -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
@@ -49,6 +49,7 @@
 JNIEXPORT jlong JNICALL Java_sun_security_pkcs11_Secmod_nssGetLibraryHandle
   (JNIEnv *env, jclass thisClass, jstring jLibName)
 {
+    void *hModule;
     const char *libName = (*env)->GetStringUTFChars(env, jLibName, NULL);
     if (libName == NULL) {
         return 0L;
@@ -56,9 +57,9 @@
 
     // look up existing handle only, do not load
 #if defined(AIX)
-    void *hModule = dlopen(libName, RTLD_LAZY);
+    hModule = dlopen(libName, RTLD_LAZY);
 #else
-    void *hModule = dlopen(libName, RTLD_NOLOAD);
+    hModule = dlopen(libName, RTLD_NOLOAD);
 #endif
     dprintf2("-handle for %s: %u\n", libName, hModule);
     (*env)->ReleaseStringUTFChars(env, jLibName, libName);
--- a/jdk/src/jdk.crypto.pkcs11/windows/native/libj2pkcs11/j2secmod_md.c	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/src/jdk.crypto.pkcs11/windows/native/libj2pkcs11/j2secmod_md.c	Mon Aug 29 08:53:32 2016 -0700
@@ -31,6 +31,9 @@
 
 #include "j2secmod.h"
 
+extern void throwNullPointerException(JNIEnv *env, const char *message);
+extern void throwIOException(JNIEnv *env, const char *message);
+
 void *findFunction(JNIEnv *env, jlong jHandle, const char *functionName) {
     HINSTANCE hModule = (HINSTANCE)jHandle;
     void *fAddress = GetProcAddress(hModule, functionName);
--- a/jdk/src/jdk.internal.opt/share/classes/module-info.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/src/jdk.internal.opt/share/classes/module-info.java	Mon Aug 29 08:53:32 2016 -0700
@@ -24,5 +24,5 @@
  */
 
 module jdk.internal.opt {
-    exports jdk.internal.joptsimple to jdk.jlink;
+    exports jdk.internal.joptsimple to jdk.jlink, jdk.jshell;
 }
--- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/builder/DefaultImageBuilder.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/builder/DefaultImageBuilder.java	Mon Aug 29 08:53:32 2016 -0700
@@ -78,28 +78,21 @@
         private final List<String> args;
         private final Set<String> modules;
 
-        public DefaultExecutableImage(Path home, Set<String> modules) {
-            this(home, modules, createArgs(home));
-        }
-
-        private DefaultExecutableImage(Path home, Set<String> modules,
-                List<String> args) {
+        DefaultExecutableImage(Path home, Set<String> modules) {
             Objects.requireNonNull(home);
-            Objects.requireNonNull(args);
             if (!Files.exists(home)) {
                 throw new IllegalArgumentException("Invalid image home");
             }
             this.home = home;
             this.modules = Collections.unmodifiableSet(modules);
-            this.args = Collections.unmodifiableList(args);
+            this.args = createArgs(home);
         }
 
         private static List<String> createArgs(Path home) {
             Objects.requireNonNull(home);
-            List<String> javaArgs = new ArrayList<>();
-            javaArgs.add(home.resolve("bin").
-                    resolve(getJavaProcessName()).toString());
-            return javaArgs;
+            Path binDir = home.resolve("bin");
+            String java = Files.exists(binDir.resolve("java"))? "java" : "java.exe";
+            return List.of(binDir.resolve(java).toString());
         }
 
         @Override
@@ -130,6 +123,7 @@
     private final Path root;
     private final Path mdir;
     private final Set<String> modules = new HashSet<>();
+    private String targetOsName;
 
     /**
      * Default image builder constructor.
@@ -171,6 +165,11 @@
     @Override
     public void storeFiles(ResourcePool files) {
         try {
+            // populate release properties up-front. targetOsName
+            // field is assigned from there and used elsewhere.
+            Properties release = releaseProperties(files);
+            Path bin = root.resolve("bin");
+
             files.entries().forEach(f -> {
                 if (!f.type().equals(ResourcePoolEntry.Type.CLASS_OR_RESOURCE)) {
                     try {
@@ -186,11 +185,11 @@
                     modules.add(m.name());
                 }
             });
-            storeFiles(modules, releaseProperties(files));
+
+            storeFiles(modules, release);
 
             if (Files.getFileStore(root).supportsFileAttributeView(PosixFileAttributeView.class)) {
                 // launchers in the bin directory need execute permission
-                Path bin = root.resolve("bin");
                 if (Files.isDirectory(bin)) {
                     Files.list(bin)
                             .filter(f -> !f.toString().endsWith(".diz"))
@@ -208,7 +207,11 @@
                 }
             }
 
-            prepareApplicationFiles(files, modules);
+            // If native files are stripped completely, <root>/bin dir won't exist!
+            // So, don't bother generating launcher scripts.
+            if (Files.isDirectory(bin)) {
+                 prepareApplicationFiles(files, modules);
+            }
         } catch (IOException ex) {
             throw new PluginException(ex);
         }
@@ -226,6 +229,11 @@
             props.setProperty("JAVA_VERSION", System.getProperty("java.version"));
         });
 
+        this.targetOsName = props.getProperty("OS_NAME");
+        if (this.targetOsName == null) {
+            throw new PluginException("TargetPlatform attribute is missing for java.base module");
+        }
+
         Optional<ResourcePoolEntry> release = pool.findEntry("/java.base/release");
         if (release.isPresent()) {
             try (InputStream is = release.get().content()) {
@@ -373,7 +381,7 @@
         Files.createLink(dstFile, target);
     }
 
-    private static String nativeDir(String filename) {
+    private String nativeDir(String filename) {
         if (isWindows()) {
             if (filename.endsWith(".dll") || filename.endsWith(".diz")
                     || filename.endsWith(".pdb") || filename.endsWith(".map")) {
@@ -386,8 +394,8 @@
         }
     }
 
-    private static boolean isWindows() {
-        return System.getProperty("os.name").startsWith("Windows");
+    private boolean isWindows() {
+        return targetOsName.startsWith("Windows");
     }
 
     /**
@@ -452,12 +460,10 @@
         }
     }
 
-    private static String getJavaProcessName() {
-        return isWindows() ? "java.exe" : "java";
-    }
-
     public static ExecutableImage getExecutableImage(Path root) {
-        if (Files.exists(root.resolve("bin").resolve(getJavaProcessName()))) {
+        Path binDir = root.resolve("bin");
+        if (Files.exists(binDir.resolve("java")) ||
+            Files.exists(binDir.resolve("java.exe"))) {
             return new DefaultExecutableImage(root, retrieveModules(root));
         }
         return null;
--- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/ImagePluginStack.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/ImagePluginStack.java	Mon Aug 29 08:53:32 2016 -0700
@@ -172,7 +172,7 @@
     private final Plugin lastSorter;
     private final List<Plugin> plugins = new ArrayList<>();
     private final List<ResourcePrevisitor> resourcePrevisitors = new ArrayList<>();
-
+    private final boolean validate;
 
     public ImagePluginStack() {
         this(null, Collections.emptyList(), null);
@@ -181,6 +181,13 @@
     public ImagePluginStack(ImageBuilder imageBuilder,
             List<Plugin> plugins,
             Plugin lastSorter) {
+        this(imageBuilder, plugins, lastSorter, true);
+    }
+
+    public ImagePluginStack(ImageBuilder imageBuilder,
+            List<Plugin> plugins,
+            Plugin lastSorter,
+            boolean validate) {
         this.imageBuilder = Objects.requireNonNull(imageBuilder);
         this.lastSorter = lastSorter;
         this.plugins.addAll(Objects.requireNonNull(plugins));
@@ -190,6 +197,7 @@
                 resourcePrevisitors.add((ResourcePrevisitor) p);
             }
         });
+        this.validate = validate;
     }
 
     public void operate(ImageProvider provider) throws Exception {
@@ -268,6 +276,7 @@
                 frozenOrder = ((OrderedResourcePoolManager.OrderedResourcePool)resPool).getOrderedList();
             }
         }
+
         return resPool;
     }
 
@@ -458,7 +467,11 @@
             throws Exception {
         Objects.requireNonNull(original);
         Objects.requireNonNull(transformed);
-        imageBuilder.storeFiles(new LastPoolManager(transformed).resourcePool());
+        ResourcePool lastPool = new LastPoolManager(transformed).resourcePool();
+        if (validate) {
+            ResourcePoolConfiguration.validate(lastPool);
+        }
+        imageBuilder.storeFiles(lastPool);
     }
 
     public ExecutableImage getExecutableImage() throws IOException {
--- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/PathResourcePoolEntry.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/PathResourcePoolEntry.java	Mon Aug 29 08:53:32 2016 -0700
@@ -5,7 +5,7 @@
  * 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 "Classfile" exception as provided
+ * 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
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/ResourcePoolConfiguration.java	Mon Aug 29 08:53:32 2016 -0700
@@ -0,0 +1,128 @@
+/*
+ * 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 jdk.tools.jlink.internal;
+
+import java.lang.module.Configuration;
+import java.lang.module.ModuleDescriptor;
+import java.lang.module.ModuleFinder;
+import java.lang.module.ModuleReference;
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.nio.ByteBuffer;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.stream.Collectors;
+import jdk.tools.jlink.plugin.PluginException;
+import jdk.tools.jlink.plugin.ResourcePool;
+import jdk.tools.jlink.plugin.ResourcePoolEntry;
+import jdk.tools.jlink.plugin.ResourcePoolModule;
+
+final class ResourcePoolConfiguration {
+    private ResourcePoolConfiguration() {}
+
+    private static ModuleDescriptor descriptorOf(ResourcePoolModule mod) {
+        ModuleDescriptor md = mod.descriptor();
+
+        // drop hashes
+        ModuleDescriptor.Builder builder = new ModuleDescriptor.Builder(md.name());
+        md.requires().stream()
+          .forEach(builder::requires);
+        md.exports().stream()
+          .forEach(builder::exports);
+        md.uses().stream()
+          .forEach(builder::uses);
+        md.provides().values().stream()
+          .forEach(builder::provides);
+
+        // build the proper concealed packages
+        Set<String> exps = md.exports().stream()
+            .map(ModuleDescriptor.Exports::source)
+            .collect(Collectors.toSet());
+
+        mod.packages().stream()
+           .filter(pn -> !exps.contains(pn))
+           .forEach(builder::conceals);
+
+        md.version().ifPresent(builder::version);
+        md.mainClass().ifPresent(builder::mainClass);
+        md.osName().ifPresent(builder::osName);
+        md.osArch().ifPresent(builder::osArch);
+        md.osVersion().ifPresent(builder::osVersion);
+
+        return builder.build();
+    }
+
+    private static ModuleReference moduleReference(ModuleDescriptor desc) {
+        return new ModuleReference(desc, null, () -> {
+            IOException ioe = new IOException("<module reader unsupported>");
+            throw new UncheckedIOException(ioe);
+        });
+    }
+
+    private static Map<String, ModuleReference> allModRefs(ResourcePool pool) {
+        return pool.moduleView().modules().
+            collect(Collectors.toMap(ResourcePoolModule::name,
+                m -> moduleReference(descriptorOf(m))));
+    }
+
+    private static void checkPackages(ResourcePool pool) {
+        // check that each resource pool module's packages()
+        // returns a set that is consistent with the module
+        // descriptor of that module.
+
+        pool.moduleView().modules().forEach(m -> {
+            ModuleDescriptor desc = m.descriptor();
+            if (!desc.packages().equals(m.packages())) {
+                throw new RuntimeException("Module " + m.name() +
+                   "'s descriptor returns inconsistent package set");
+            }
+        });
+    }
+
+    static Configuration validate(ResourcePool pool) {
+        checkPackages(pool);
+        final Map<String, ModuleReference> nameToModRef = allModRefs(pool);
+        final Set<ModuleReference> allRefs = new HashSet<>(nameToModRef.values());
+
+        final ModuleFinder finder = new ModuleFinder() {
+            @Override
+            public Optional<ModuleReference> find(String name) {
+                return Optional.ofNullable(nameToModRef.get(name));
+            }
+
+            @Override
+            public Set<ModuleReference> findAll() {
+                return allRefs;
+            }
+        };
+
+        return Configuration.empty().resolveRequires(
+            finder, ModuleFinder.of(), nameToModRef.keySet());
+    }
+}
--- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/plugins/GenerateJLIClassesPlugin.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/plugins/GenerateJLIClassesPlugin.java	Mon Aug 29 08:53:32 2016 -0700
@@ -24,7 +24,11 @@
  */
 package jdk.tools.jlink.internal.plugins;
 
+import java.io.File;
+import java.io.IOException;
 import java.lang.invoke.MethodType;
+import java.nio.file.Files;
+import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.EnumSet;
 import java.util.HashMap;
@@ -32,6 +36,7 @@
 import java.util.Map;
 import java.util.Set;
 import java.util.stream.Collectors;
+import java.util.stream.Stream;
 import jdk.internal.misc.SharedSecrets;
 import jdk.internal.misc.JavaLangInvokeAccess;
 import jdk.tools.jlink.plugin.ResourcePoolEntry;
@@ -47,15 +52,9 @@
 
     private static final String NAME = "generate-jli-classes";
 
-    private static final String BMH_PARAM = "bmh";
-
-    private static final String BMH_SPECIES_PARAM = "bmh-species";
-
-    private static final String DMH_PARAM = "dmh";
-
     private static final String DESCRIPTION = PluginsResourceBundle.getDescription(NAME);
 
-    private static final String DIRECT_METHOD_HANDLE = "java/lang/invoke/DirectMethodHandle$Holder";
+    private static final String DIRECT_HOLDER = "java/lang/invoke/DirectMethodHandle$Holder";
     private static final String DMH_INVOKE_VIRTUAL = "invokeVirtual";
     private static final String DMH_INVOKE_STATIC = "invokeStatic";
     private static final String DMH_INVOKE_SPECIAL = "invokeSpecial";
@@ -63,15 +62,17 @@
     private static final String DMH_INVOKE_INTERFACE = "invokeInterface";
     private static final String DMH_INVOKE_STATIC_INIT = "invokeStaticInit";
 
-    private static final String DELEGATING_METHOD_HANDLE = "java/lang/invoke/DelegatingMethodHandle$Holder";
-
-    private static final String BASIC_FORMS_HANDLE = "java/lang/invoke/LambdaForm$Holder";
+    private static final String DELEGATING_HOLDER = "java/lang/invoke/DelegatingMethodHandle$Holder";
+    private static final String BASIC_FORMS_HOLDER = "java/lang/invoke/LambdaForm$Holder";
+    private static final String INVOKERS_HOLDER = "java/lang/invoke/Invokers$Holder";
 
     private static final JavaLangInvokeAccess JLIA
             = SharedSecrets.getJavaLangInvokeAccess();
 
     List<String> speciesTypes;
 
+    List<String> invokerTypes;
+
     Map<String, List<String>> dmhMethods;
 
     public GenerateJLIClassesPlugin() {
@@ -117,21 +118,29 @@
     }
 
     /**
+     * @return the default invoker forms to generate.
+     */
+    private static List<String> defaultInvokers() {
+        return List.of("LL_L", "LL_I", "LILL_I", "L6_L");
+    }
+
+    /**
      * @return the list of default DirectMethodHandle methods to generate.
      */
-    public static Map<String, List<String>> defaultDMHMethods() {
+    private static Map<String, List<String>> defaultDMHMethods() {
         return Map.of(
-            DMH_INVOKE_VIRTUAL, List.of("_L", "L_L", "LI_I", "LL_V"),
-            DMH_INVOKE_SPECIAL, List.of("L_I", "L_L", "LF_L", "LD_L", "LL_L",
-                "L3_L", "L4_L", "L5_L", "L6_L", "L7_L", "LI_I", "LI_L", "LIL_I",
-                "LII_I", "LII_L", "LLI_L", "LLI_I", "LILI_I", "LIIL_L",
-                "LIILL_L", "LIILL_I", "LIIL_I", "LILIL_I", "LILILL_I",
-                "LILII_I", "LI3_I", "LI3L_I", "LI3LL_I", "LI3_L", "LI4_I"),
-            DMH_INVOKE_STATIC, List.of("II_I", "IL_I", "ILIL_I", "ILII_I",
-                "_I", "_L", "_V", "D_L", "F_L", "I_I", "II_L", "LI_L",
-                "L_V", "L_L", "LL_L", "L3_L", "L4_L", "L5_L", "L6_L",
-                "L7_L", "L8_L", "L9_L", "L9I_L", "L9II_L", "L9IIL_L",
-                "L10_L", "L11_L", "L12_L", "L13_L", "L13I_L", "L13II_L")
+            DMH_INVOKE_VIRTUAL, List.of("L_L", "LL_L", "LLI_I", "L3_V"),
+            DMH_INVOKE_SPECIAL, List.of("LL_I", "LL_L", "LLF_L", "LLD_L", "L3_L",
+                "L4_L", "L5_L", "L6_L", "L7_L", "L8_L", "LLI_I", "LLI_L",
+                "LLIL_I", "LLII_I", "LLII_L", "L3I_L", "L3I_I", "LLILI_I",
+                "LLIIL_L", "LLIILL_L", "LLIILL_I", "LLIIL_I", "LLILIL_I",
+                "LLILILL_I", "LLILII_I", "LLI3_I", "LLI3L_I", "LLI3LL_I",
+                "LLI3_L", "LLI4_I"),
+            DMH_INVOKE_STATIC, List.of("LII_I", "LIL_I", "LILIL_I", "LILII_I",
+                "L_I", "L_L", "L_V", "LD_L", "LF_L", "LI_I", "LII_L", "LLI_L",
+                "LL_V", "LL_L", "L3_L", "L4_L", "L5_L", "L6_L", "L7_L",
+                "L8_L", "L9_L", "L10_L", "L10I_L", "L10II_L", "L10IIL_L",
+                "L11_L", "L12_L", "L13_L", "L14_L", "L14I_L", "L14II_L")
         );
     }
 
@@ -150,72 +159,91 @@
     public void configure(Map<String, String> config) {
         String mainArgument = config.get(NAME);
 
-        // Enable by default
-        boolean bmhEnabled = true;
-        boolean dmhEnabled = true;
-        if (mainArgument != null) {
-            List<String> args = Arrays.asList(mainArgument.split(","));
-            if (!args.contains(BMH_PARAM)) {
-                bmhEnabled = false;
+        if (mainArgument != null && mainArgument.startsWith("@")) {
+            File file = new File(mainArgument.substring(1));
+            if (file.exists()) {
+                speciesTypes = new ArrayList<>();
+                invokerTypes = new ArrayList<>();
+                dmhMethods = new HashMap<>();
+                Stream<String> lines = fileLines(file);
+
+                lines.map(line -> line.split(" "))
+                    .forEach(parts -> {
+                        switch (parts[0]) {
+                            case "[BMH_RESOLVE]":
+                                speciesTypes.add(expandSignature(parts[1]));
+                                break;
+                            case "[LF_RESOLVE]":
+                                String methodType = parts[3];
+                                validateMethodType(methodType);
+                                if (parts[1].contains("Invokers")) {
+                                    invokerTypes.add(methodType);
+                                } else if (parts[1].contains("DirectMethodHandle")) {
+                                    String dmh = parts[2];
+                                    // ignore getObject etc for now (generated
+                                    // by default)
+                                    if (DMH_METHOD_TYPE_MAP.containsKey(dmh)) {
+                                        addDMHMethodType(dmh, methodType);
+                                    }
+                                }
+                                break;
+                            default: break; // ignore
+                        }
+                });
             }
-            if (!args.contains(DMH_PARAM)) {
-                dmhEnabled = false;
-            }
-        }
-
-        if (!bmhEnabled) {
-            speciesTypes = List.of();
         } else {
-            String args = config.get(BMH_SPECIES_PARAM);
-            List<String> bmhSpecies;
-            if (args != null && !args.isEmpty()) {
-                bmhSpecies = Arrays.stream(args.split(","))
-                    .map(String::trim)
-                    .filter(s -> !s.isEmpty())
-                    .collect(Collectors.toList());
-            } else {
-                bmhSpecies = defaultSpecies();
-            }
-
+            List<String> bmhSpecies = defaultSpecies();
             // Expand BMH species signatures
             speciesTypes = bmhSpecies.stream()
                     .map(type -> expandSignature(type))
                     .collect(Collectors.toList());
-        }
 
-        // DirectMethodHandles
-        if (!dmhEnabled) {
-            dmhMethods = Map.of();
-        } else {
-            dmhMethods = new HashMap<>();
-            for (String dmhParam : DMH_METHOD_TYPE_MAP.keySet()) {
-                String args = config.get(dmhParam);
-                if (args != null && !args.isEmpty()) {
-                    List<String> dmhMethodTypes = Arrays.stream(args.split(","))
-                            .map(String::trim)
-                            .filter(s -> !s.isEmpty())
-                            .collect(Collectors.toList());
-                    dmhMethods.put(dmhParam, dmhMethodTypes);
-                    // Validation check
-                    for (String type : dmhMethodTypes) {
-                        String[] typeParts = type.split("_");
-                        // check return type (second part)
-                        if (typeParts.length != 2 || typeParts[1].length() != 1
-                                || "LJIFDV".indexOf(typeParts[1].charAt(0)) == -1) {
-                            throw new PluginException(
-                                    "Method type signature must be of form [LJIFD]*_[LJIFDV]");
-                        }
-                        // expand and check arguments (first part)
-                        expandSignature(typeParts[0]);
-                    }
-                }
-            }
-            if (dmhMethods.isEmpty()) {
-                dmhMethods = defaultDMHMethods();
+            invokerTypes = defaultInvokers();
+            validateMethodTypes(invokerTypes);
+
+            dmhMethods = defaultDMHMethods();
+            for (List<String> dmhMethodTypes : dmhMethods.values()) {
+                validateMethodTypes(dmhMethodTypes);
             }
         }
     }
 
+    private void addDMHMethodType(String dmh, String methodType) {
+        validateMethodType(methodType);
+        List<String> methodTypes = dmhMethods.get(dmh);
+        if (methodTypes == null) {
+            methodTypes = new ArrayList<>();
+            dmhMethods.put(dmh, methodTypes);
+        }
+        methodTypes.add(methodType);
+    }
+
+    private Stream<String> fileLines(File file) {
+        try {
+            return Files.lines(file.toPath());
+        } catch (IOException io) {
+            throw new PluginException("Couldn't read file");
+        }
+    }
+
+    private void validateMethodTypes(List<String> dmhMethodTypes) {
+        for (String type : dmhMethodTypes) {
+            validateMethodType(type);
+        }
+    }
+
+    private void validateMethodType(String type) {
+        String[] typeParts = type.split("_");
+        // check return type (second part)
+        if (typeParts.length != 2 || typeParts[1].length() != 1
+                || "LJIFDV".indexOf(typeParts[1].charAt(0)) == -1) {
+            throw new PluginException(
+                    "Method type signature must be of form [LJIFD]*_[LJIFDV]");
+        }
+        // expand and check arguments (first part)
+        expandSignature(typeParts[0]);
+    }
+
     private static void requireBasicType(char c) {
         if ("LIJFD".indexOf(c) < 0) {
             throw new PluginException(
@@ -228,9 +256,10 @@
         // Copy all but DMH_ENTRY to out
         in.transformAndCopy(entry -> {
                 // filter out placeholder entries
-                if (entry.path().equals(DIRECT_METHOD_HANDLE_ENTRY) ||
-                    entry.path().equals(DELEGATING_METHOD_HANDLE_ENTRY) ||
-                    entry.path().equals(BASIC_FORMS_HANDLE_ENTRY)) {
+                if (entry.path().equals(DIRECT_METHOD_HOLDER_ENTRY) ||
+                    entry.path().equals(DELEGATING_METHOD_HOLDER_ENTRY) ||
+                    entry.path().equals(INVOKERS_HOLDER_ENTRY) ||
+                    entry.path().equals(BASIC_FORMS_HOLDER_ENTRY)) {
                     return null;
                 } else {
                     return entry;
@@ -265,42 +294,72 @@
         for (List<String> entry : dmhMethods.values()) {
             count += entry.size();
         }
-        MethodType[] methodTypes = new MethodType[count];
+        MethodType[] directMethodTypes = new MethodType[count];
         int[] dmhTypes = new int[count];
         int index = 0;
         for (Map.Entry<String, List<String>> entry : dmhMethods.entrySet()) {
             String dmhType = entry.getKey();
             for (String type : entry.getValue()) {
-                methodTypes[index] = asMethodType(type);
+                // The DMH type to actually ask for is retrieved by removing
+                // the first argument, which needs to be of Object.class
+                MethodType mt = asMethodType(type);
+                if (mt.parameterCount() < 1 ||
+                    mt.parameterType(0) != Object.class) {
+                    throw new PluginException(
+                            "DMH type parameter must start with L");
+                }
+                directMethodTypes[index] = mt.dropParameterTypes(0, 1);
                 dmhTypes[index] = DMH_METHOD_TYPE_MAP.get(dmhType);
                 index++;
             }
         }
+        MethodType[] invokerMethodTypes = new MethodType[this.invokerTypes.size()];
+        for (int i = 0; i < invokerTypes.size(); i++) {
+            // The invoker type to ask for is retrieved by removing the first
+            // and the last argument, which needs to be of Object.class
+            MethodType mt = asMethodType(invokerTypes.get(i));
+            final int lastParam = mt.parameterCount() - 1;
+            if (mt.parameterCount() < 2 ||
+                    mt.parameterType(0) != Object.class ||
+                    mt.parameterType(lastParam) != Object.class) {
+                throw new PluginException(
+                        "Invoker type parameter must start and end with L");
+            }
+            mt = mt.dropParameterTypes(lastParam, lastParam + 1);
+            invokerMethodTypes[i] = mt.dropParameterTypes(0, 1);
+        }
         try {
             byte[] bytes = JLIA.generateDirectMethodHandleHolderClassBytes(
-                    DIRECT_METHOD_HANDLE, methodTypes, dmhTypes);
+                    DIRECT_HOLDER, directMethodTypes, dmhTypes);
             ResourcePoolEntry ndata = ResourcePoolEntry
-                    .create(DIRECT_METHOD_HANDLE_ENTRY, bytes);
+                    .create(DIRECT_METHOD_HOLDER_ENTRY, bytes);
             out.add(ndata);
 
             bytes = JLIA.generateDelegatingMethodHandleHolderClassBytes(
-                    DELEGATING_METHOD_HANDLE, methodTypes);
-            ndata = ResourcePoolEntry.create(DELEGATING_METHOD_HANDLE_ENTRY, bytes);
+                    DELEGATING_HOLDER, directMethodTypes);
+            ndata = ResourcePoolEntry.create(DELEGATING_METHOD_HOLDER_ENTRY, bytes);
             out.add(ndata);
 
-            bytes = JLIA.generateBasicFormsClassBytes(BASIC_FORMS_HANDLE);
-            ndata = ResourcePoolEntry.create(BASIC_FORMS_HANDLE_ENTRY, bytes);
+            bytes = JLIA.generateInvokersHolderClassBytes(INVOKERS_HOLDER,
+                    invokerMethodTypes);
+            ndata = ResourcePoolEntry.create(INVOKERS_HOLDER_ENTRY, bytes);
+            out.add(ndata);
+
+            bytes = JLIA.generateBasicFormsClassBytes(BASIC_FORMS_HOLDER);
+            ndata = ResourcePoolEntry.create(BASIC_FORMS_HOLDER_ENTRY, bytes);
             out.add(ndata);
         } catch (Exception ex) {
             throw new PluginException(ex);
         }
     }
-    private static final String DIRECT_METHOD_HANDLE_ENTRY =
-            "/java.base/" + DIRECT_METHOD_HANDLE + ".class";
-    private static final String DELEGATING_METHOD_HANDLE_ENTRY =
-            "/java.base/" + DELEGATING_METHOD_HANDLE + ".class";
-    private static final String BASIC_FORMS_HANDLE_ENTRY =
-            "/java.base/" + BASIC_FORMS_HANDLE + ".class";
+    private static final String DIRECT_METHOD_HOLDER_ENTRY =
+            "/java.base/" + DIRECT_HOLDER + ".class";
+    private static final String DELEGATING_METHOD_HOLDER_ENTRY =
+            "/java.base/" + DELEGATING_HOLDER + ".class";
+    private static final String BASIC_FORMS_HOLDER_ENTRY =
+            "/java.base/" + BASIC_FORMS_HOLDER + ".class";
+    private static final String INVOKERS_HOLDER_ENTRY =
+            "/java.base/" + INVOKERS_HOLDER + ".class";
 
     // Convert LL -> LL, L3 -> LLL
     private static String expandSignature(String signature) {
--- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/resources/plugins.properties	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/resources/plugins.properties	Mon Aug 29 08:53:32 2016 -0700
@@ -56,7 +56,7 @@
 
 copy-files.description=\
 If files to copy are not absolute path, JDK home dir is used.\n\
-e.g.: jrt-fs.jar,LICENSE,/home/me/myfile.txt=somewehere/conf.txt
+e.g.: jrt-fs.jar,LICENSE,/home/me/myfile.txt=somewhere/conf.txt
 
 exclude-files.argument=<pattern-list> of files to exclude
 
@@ -68,10 +68,12 @@
 exclude-resources.description=\
 Specify resources to exclude. e.g.: **.jcov,glob:**/META-INF/**
 
-generate-jli-classes.argument=<bmh[:bmh-species=LL,L3,...]>
+generate-jli-classes.argument=<@filename>
 
 generate-jli-classes.description=\
-Concrete java.lang.invoke classes to generate
+Takes a file hinting to jlink what java.lang.invoke classes to pre-generate. If\n\
+this flag is not specified a default set of classes will be generated, so to \n\
+disable pre-generation supply the name of an empty or non-existing file
 
 installed-modules.description=Fast loading of module descriptors (always enabled)
 
--- a/jdk/src/jdk.zipfs/share/classes/jdk/nio/zipfs/JarFileSystem.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/src/jdk.zipfs/share/classes/jdk/nio/zipfs/JarFileSystem.java	Mon Aug 29 08:53:32 2016 -0700
@@ -165,8 +165,8 @@
             walk(inode.child, process);
         } else {
             process.accept(inode);
-            walk(inode.sibling, process);
         }
+        walk(inode.sibling, process);
     }
 
     /**
--- a/jdk/test/ProblemList.txt	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/test/ProblemList.txt	Mon Aug 29 08:53:32 2016 -0700
@@ -124,10 +124,6 @@
 # jdk_lang
 
 java/lang/StringCoding/CheckEncodings.sh                        7008363 generic-all
-java/lang/invoke/VarHandles/VarHandleTestMethodHandleAccessBoolean.java	8160690 generic-all
-java/lang/invoke/VarHandles/VarHandleTestMethodHandleAccessByte.java	8160690 generic-all
-java/lang/invoke/VarHandles/VarHandleTestMethodHandleAccessChar.java	8160690 generic-all
-java/lang/invoke/VarHandles/VarHandleTestMethodHandleAccessShort.java	8160690 generic-all
 
 ############################################################################
 
@@ -211,8 +207,6 @@
 
 java/rmi/transport/dgcDeadLock/DGCDeadLock.java                 8029360 macosx-all
 
-sun/rmi/runtime/Log/6409194/NoConsoleOutput.java                8164124 windows-all
-
 ############################################################################
 
 # jdk_security
--- a/jdk/test/com/sun/jdi/CatchPatternTest.sh	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/test/com/sun/jdi/CatchPatternTest.sh	Mon Aug 29 08:53:32 2016 -0700
@@ -87,7 +87,12 @@
    cmd stop in ${classname}.partTwo
    runToBkpt
    cmd ignore uncaught java.lang.Throwable
-   cmd catch all java.lang.I*
+   # Instead of matching java.lang.I* we use two more specific
+   # patterns here. The reason is to avoid matching IncompatibleClassChangeError
+   # (or the subclass NoSuchMethodError) thrown by the
+   # java.lang.invoke infrastructure.
+   cmd catch all java.lang.Il*
+   cmd catch all java.lang.Ind*
    cmd cont
    cmd cont
    cmd cont
--- a/jdk/test/com/sun/jdi/ClassesByName2Test.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/test/com/sun/jdi/ClassesByName2Test.java	Mon Aug 29 08:53:32 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 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
@@ -28,8 +28,7 @@
  *
  *  @author Tim Bell (based on ClassesByName by Robert Field)
  *
- *  @modules java.corba
- *           jdk.jdi
+ *  @modules jdk.jdi
  *  @run build TestScaffold VMConnection TargetListener TargetAdapter
  *  @run compile -g ClassesByName2Test.java
  *  @run driver ClassesByName2Test
@@ -70,10 +69,14 @@
                 };
 
             Thread two = new Thread ("TWO") {
-                    public void run () {
-                        javax.rmi.CORBA.Util.getCodebase(this.getClass());
+                public void run () {
+                    try {
+                        String s = String.format("%02x", 0xff);
+                    } catch (Exception e) {
+                        e.printStackTrace();
                     }
-                };
+                }
+            };
 
             two.start();
             one.start();
--- a/jdk/test/java/lang/StackWalker/VerifyStackTrace.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/test/java/lang/StackWalker/VerifyStackTrace.java	Mon Aug 29 08:53:32 2016 -0700
@@ -205,12 +205,13 @@
                     .replaceAll("java.base@(\\d+\\.){0,3}(\\d+)/", "java.base/")
                     .replaceAll("/[0-9]+\\.run", "/xxxxxxxx.run")
                     .replaceAll("/[0-9]+\\.invoke", "/xxxxxxxx.invoke")
-                    // DMHs may or may not be pre-generated, making frames differ
+                    // LFs may or may not be pre-generated, making frames differ
                     .replaceAll("DirectMethodHandle\\$Holder", "LambdaForm\\$DMH")
-                    .replaceAll("DMH\\.invoke", "DMH/xxxxxxxx.invoke")
+                    .replaceAll("Invokers\\$Holder", "LambdaForm\\$MH")
+                    .replaceAll("MH\\.invoke", "MH/xxxxxxxx.invoke")
                     // invoke frames may or may not have basic method type
                     // information encoded for diagnostic purposes
-                    .replaceAll("xx\\.invoke([A-Za-z]*)_[A-Z]+_[A-Z]", "xx.invoke$1")
+                    .replaceAll("xx\\.invoke([A-Za-z]*)_[A-Z_]+", "xx.invoke$1")
                     .replaceAll("\\$[0-9]+", "\\$??");
         } else {
             return produced;
--- a/jdk/test/java/lang/invoke/LFCaching/LFSingleThreadCachingTest.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/test/java/lang/invoke/LFCaching/LFSingleThreadCachingTest.java	Mon Aug 29 08:53:32 2016 -0700
@@ -23,7 +23,6 @@
 
 /*
  * @test LFSingleThreadCachingTest
- * @ignore 8129523
  * @bug 8046703
  * @key randomness
  * @summary Test verifies that lambda forms are cached when run with single thread
@@ -33,7 +32,7 @@
  * @build LambdaFormTestCase
  * @build LFCachingTestCase
  * @build LFSingleThreadCachingTest
- * @run main/othervm LFSingleThreadCachingTest
+ * @run main/othervm -XX:ReservedCodeCacheSize=128m LFSingleThreadCachingTest
  */
 
 import java.lang.invoke.MethodHandle;
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/net/HttpCookie/CookieNegativeMaxAge.java	Mon Aug 29 08:53:32 2016 -0700
@@ -0,0 +1,56 @@
+/*
+ * 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 8005068
+ * @summary Check that any negative maxAge is treated as "unspecified" and
+ * if header contains cookie with "expires" attribute in the past then cookie
+ * is created with maxAge=0 meaning it is specified to be immediately expired.
+ * @run main CookieNegativeMaxAge
+ */
+
+
+import java.net.HttpCookie;
+import java.util.List;
+
+public class CookieNegativeMaxAge {
+
+    public static void main(String... args) {
+        HttpCookie cookie = new HttpCookie("testCookie", "value");
+        cookie.setMaxAge(Integer.MIN_VALUE);
+        if (cookie.hasExpired()) {
+            throw new RuntimeException("Cookie has unexpectedly expired");
+        }
+
+        List<HttpCookie> cookies = HttpCookie.parse("Set-Cookie: " +
+                "expiredCookie=value; expires=Thu, 01 Jan 1970 00:00:00 GMT");
+        if (cookies.size() == 1) {
+            if (cookies.get(0).getMaxAge() != 0) {
+                throw new RuntimeException("Cookie maxAge expected to be 0");
+            }
+        } else {
+            throw new RuntimeException("Header was incorrectly parsed");
+        }
+    }
+}
--- a/jdk/test/java/net/MulticastSocket/NoLoopbackPackets.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/test/java/net/MulticastSocket/NoLoopbackPackets.java	Mon Aug 29 08:53:32 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 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
@@ -68,6 +68,7 @@
 
         MulticastSocket msock = null;
         List<SocketAddress> failedGroups = new ArrayList<SocketAddress>();
+        Sender sender = null;
         try {
             msock = new MulticastSocket();
             int port = msock.getLocalPort();
@@ -80,9 +81,8 @@
             groups.add(new InetSocketAddress(InetAddress.getByName("::ffff:224.1.1.2"), port));
             groups.add(new InetSocketAddress(InetAddress.getByName("ff02::1:1"), port));
 
-            Thread sender = new Thread(new Sender(groups));
-            sender.setDaemon(true); // we want sender to stop when main thread exits
-            sender.start();
+            sender = new Sender(groups);
+            new Thread(sender).start();
 
             // Now try to receive multicast packets. we should not see any of them
             // since we disable loopback mode.
@@ -107,6 +107,9 @@
             }
         } finally {
             if (msock != null) try { msock.close(); } catch (Exception e) {}
+            if (sender != null) {
+                sender.stop();
+            }
         }
 
         if (failedGroups.size() > 0) {
@@ -119,6 +122,7 @@
 
     static class Sender implements Runnable {
         private List<SocketAddress> sendToGroups;
+        private volatile boolean stop;
 
         public Sender(List<SocketAddress> groups) {
             sendToGroups = groups;
@@ -136,7 +140,7 @@
 
                 MulticastSocket msock = new MulticastSocket();
                 msock.setLoopbackMode(true);    // disable loopback mode
-                for (;;) {
+                while (!stop) {
                     for (DatagramPacket packet : packets) {
                         msock.send(packet);
                     }
@@ -147,5 +151,9 @@
                 throw new RuntimeException(e);
             }
         }
+
+        void stop() {
+            stop = true;
+        }
     }
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/net/httpclient/ProxyAuthTest.java	Mon Aug 29 08:53:32 2016 -0700
@@ -0,0 +1,174 @@
+/*
+ * 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
+ */
+
+/*
+ * @test
+ * @bug 8163561
+ * @modules java.base/sun.net.www
+ * @summary Verify that Proxy-Authenticate header is correctly handled
+ *
+ * @run main/othervm ProxyAuthTest
+ */
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.OutputStreamWriter;
+import java.io.PrintWriter;
+import java.net.Authenticator;
+import java.net.InetSocketAddress;
+import java.net.PasswordAuthentication;
+import java.net.ProxySelector;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.net.URI;
+import java.net.http.HttpClient;
+import java.net.http.HttpResponse;
+import java.util.Base64;
+
+import sun.net.www.MessageHeader;
+
+public class ProxyAuthTest {
+    private static final String AUTH_USER = "user";
+    private static final String AUTH_PASSWORD = "password";
+
+    public static void main(String[] args) throws Exception {
+        try (ServerSocket ss = new ServerSocket(0)) {
+            int port = ss.getLocalPort();
+            MyProxy proxy = new MyProxy(ss);
+            (new Thread(proxy)).start();
+            System.out.println("Proxy listening port " + port);
+
+            Auth auth = new Auth();
+            InetSocketAddress paddr = new InetSocketAddress("localhost", port);
+
+            URI uri = new URI("http://www.google.ie/");
+            HttpClient client = HttpClient.create()
+                    .proxy(ProxySelector.of(paddr))
+                    .authenticator(auth)
+                    .build();
+            HttpResponse resp = client.request(uri)
+                    .GET()
+                    .responseAsync()
+                    .get();
+            if (resp.statusCode() != 404) {
+                throw new RuntimeException("Unexpected status code: " + resp.statusCode());
+            }
+
+            if (auth.isCalled) {
+                System.out.println("Authenticator is called");
+            } else {
+                throw new RuntimeException("Authenticator is not called");
+            }
+
+            if (!proxy.matched) {
+                throw new RuntimeException("Proxy authentication failed");
+            }
+        }
+    }
+
+    static class Auth extends Authenticator {
+        private volatile boolean isCalled;
+
+        @Override
+        protected PasswordAuthentication getPasswordAuthentication() {
+            System.out.println("scheme: " + this.getRequestingScheme());
+            isCalled = true;
+            return new PasswordAuthentication(AUTH_USER,
+                    AUTH_PASSWORD.toCharArray());
+        }
+    }
+
+    static class MyProxy implements Runnable {
+        final ServerSocket ss;
+        private volatile boolean matched;
+
+        MyProxy(ServerSocket ss) {
+            this.ss = ss;
+        }
+
+        public void run() {
+            for (int i = 0; i < 2; i++) {
+                try (Socket s = ss.accept();
+                     InputStream in = s.getInputStream();
+                     OutputStream os = s.getOutputStream();
+                     BufferedWriter writer = new BufferedWriter(
+                             new OutputStreamWriter(os));
+                     PrintWriter out = new PrintWriter(writer);) {
+                    MessageHeader headers = new MessageHeader(in);
+                    System.out.println("Proxy: received " + headers);
+
+                    String authInfo = headers
+                            .findValue("Proxy-Authorization");
+                    if (authInfo != null) {
+                        authenticate(authInfo);
+                        out.print("HTTP/1.1 404 Not found\r\n");
+                        out.print("\r\n");
+                        System.out.println("Proxy: 404");
+                        out.flush();
+                    } else {
+                        out.print("HTTP/1.1 407 Proxy Authorization Required\r\n");
+                        out.print(
+                                "Proxy-Authenticate: Basic realm=\"a fake realm\"\r\n");
+                        out.print("\r\n");
+                        System.out.println("Proxy: Authorization required");
+                        out.flush();
+                    }
+                } catch (IOException x) {
+                    System.err.println("Unexpected IOException from proxy.");
+                    x.printStackTrace();
+                    break;
+                }
+            }
+        }
+
+        private void authenticate(String authInfo) throws IOException {
+            try {
+                authInfo.trim();
+                int ind = authInfo.indexOf(' ');
+                String recvdUserPlusPass = authInfo.substring(ind + 1).trim();
+                // extract encoded username:passwd
+                String value = new String(
+                        Base64.getMimeDecoder().decode(recvdUserPlusPass));
+                String userPlusPassword = AUTH_USER + ":" + AUTH_PASSWORD;
+                if (userPlusPassword.equals(value)) {
+                    matched = true;
+                    System.out.println("Proxy: client authentication successful");
+                } else {
+                    System.err.println(
+                            "Proxy: client authentication failed, expected ["
+                                    + userPlusPassword + "], actual [" + value
+                                    + "]");
+                }
+            } catch (Exception e) {
+                throw new IOException(
+                        "Proxy received invalid Proxy-Authorization value: "
+                                + authInfo);
+            }
+        }
+    }
+
+}
+
--- a/jdk/test/java/nio/channels/AsynchronousChannelGroup/Basic.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/test/java/nio/channels/AsynchronousChannelGroup/Basic.java	Mon Aug 29 08:53:32 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2008, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 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
@@ -119,19 +119,31 @@
             ExecutorService pool = Executors.newCachedThreadPool();
             AsynchronousChannelGroup group = AsynchronousChannelGroup
                     .withCachedThreadPool(pool, rand.nextInt(10));
-            testShutdownWithChannels(pool, group);
+            try {
+                testShutdownWithChannels(pool, group);
+            } finally {
+                group.shutdown();
+            }
         }
         for (int i = 0; i < 100; i++) {
             int nThreads = 1 + rand.nextInt(8);
             AsynchronousChannelGroup group = AsynchronousChannelGroup
                     .withFixedThreadPool(nThreads, threadFactory);
-            testShutdownWithChannels(null, group);
+            try {
+                testShutdownWithChannels(null, group);
+            } finally {
+                group.shutdown();
+            }
         }
         for (int i = 0; i < 100; i++) {
             ExecutorService pool = Executors.newCachedThreadPool();
             AsynchronousChannelGroup group = AsynchronousChannelGroup
                     .withThreadPool(pool);
-            testShutdownWithChannels(pool, group);
+            try {
+                testShutdownWithChannels(pool, group);
+            } finally {
+                group.shutdown();
+            }
         }
     }
 
@@ -164,19 +176,31 @@
             ExecutorService pool = pool = Executors.newCachedThreadPool();
             AsynchronousChannelGroup group = AsynchronousChannelGroup
                     .withCachedThreadPool(pool, rand.nextInt(5));
-            testShutdownNow(pool, group);
+            try {
+                testShutdownNow(pool, group);
+            } finally {
+                group.shutdown();
+            }
         }
         for (int i = 0; i < 10; i++) {
             int nThreads = 1 + rand.nextInt(8);
             AsynchronousChannelGroup group = AsynchronousChannelGroup
                     .withFixedThreadPool(nThreads, threadFactory);
-            testShutdownNow(null, group);
+            try {
+                testShutdownNow(null, group);
+            } finally {
+                group.shutdown();
+            }
         }
         for (int i = 0; i < 10; i++) {
             ExecutorService pool = Executors.newCachedThreadPool();
             AsynchronousChannelGroup group = AsynchronousChannelGroup
                     .withThreadPool(pool);
-            testShutdownNow(pool, group);
+            try {
+                testShutdownNow(pool, group);
+            } finally {
+                group.shutdown();
+            }
         }
     }
 
@@ -186,78 +210,78 @@
         AsynchronousChannelGroup group =
             AsynchronousChannelGroup.withFixedThreadPool(1, threadFactory);
 
-        AsynchronousSocketChannel ch = AsynchronousSocketChannel.open(group);
-        AsynchronousServerSocketChannel listener = AsynchronousServerSocketChannel.open(group);
+        try (AsynchronousSocketChannel ch = AsynchronousSocketChannel.open(group);
+                AsynchronousServerSocketChannel listener =
+                    AsynchronousServerSocketChannel.open(group)) {
 
-        // initiate accept
-        listener.bind(new InetSocketAddress(0));
-        Future<AsynchronousSocketChannel> result = listener.accept();
+            // initiate accept
+            listener.bind(new InetSocketAddress(0));
+            Future<AsynchronousSocketChannel> result = listener.accept();
 
-        // shutdown group
-        group.shutdown();
-        if (!group.isShutdown())
-            throw new RuntimeException("Group should be shutdown");
+            // shutdown group
+            group.shutdown();
+            if (!group.isShutdown())
+                throw new RuntimeException("Group should be shutdown");
 
-        // attempt to create another channel
-        try {
-            AsynchronousSocketChannel.open(group);
-            throw new RuntimeException("ShutdownChannelGroupException expected");
-        } catch (ShutdownChannelGroupException x) {
+            // attempt to create another channel
+            try {
+                AsynchronousSocketChannel.open(group);
+                throw new RuntimeException("ShutdownChannelGroupException expected");
+            } catch (ShutdownChannelGroupException x) {
+            }
+            try {
+                AsynchronousServerSocketChannel.open(group);
+                throw new RuntimeException("ShutdownChannelGroupException expected");
+            } catch (ShutdownChannelGroupException x) {
+            }
+
+            // attempt to create another channel by connecting. This should cause
+            // the accept operation to fail.
+            InetAddress lh = InetAddress.getLocalHost();
+            int port = ((InetSocketAddress)listener.getLocalAddress()).getPort();
+            InetSocketAddress isa = new InetSocketAddress(lh, port);
+            ch.connect(isa).get();
+            try {
+                result.get();
+                throw new RuntimeException("Connection was accepted");
+            } catch (ExecutionException x) {
+                Throwable cause = x.getCause();
+                if (!(cause instanceof IOException))
+                    throw new RuntimeException("Cause should be IOException");
+                cause = cause.getCause();
+                if (!(cause instanceof ShutdownChannelGroupException))
+                    throw new RuntimeException("IOException cause should be ShutdownChannelGroupException");
+            }
+
+            // initiate another accept even though channel group is shutdown.
+            Future<AsynchronousSocketChannel> res = listener.accept();
+            try {
+                res.get(3, TimeUnit.SECONDS);
+                throw new RuntimeException("TimeoutException expected");
+            } catch (TimeoutException x) {
+            }
+            // connect to the listener which should cause the accept to complete
+            AsynchronousSocketChannel.open().connect(isa);
+            try {
+                res.get();
+                throw new RuntimeException("Connection was accepted");
+            } catch (ExecutionException x) {
+                Throwable cause = x.getCause();
+                if (!(cause instanceof IOException))
+                    throw new RuntimeException("Cause should be IOException");
+                cause = cause.getCause();
+                if (!(cause instanceof ShutdownChannelGroupException))
+                    throw new RuntimeException("IOException cause should be ShutdownChannelGroupException");
+            }
+
+            // group should *not* terminate as channels are open
+            boolean terminated = group.awaitTermination(3, TimeUnit.SECONDS);
+            if (terminated) {
+                throw new RuntimeException("Group should not have terminated");
+            }
+        } finally {
+            group.shutdown();
         }
-        try {
-            AsynchronousServerSocketChannel.open(group);
-            throw new RuntimeException("ShutdownChannelGroupException expected");
-        } catch (ShutdownChannelGroupException x) {
-        }
-
-        // attempt to create another channel by connecting. This should cause
-        // the accept operation to fail.
-        InetAddress lh = InetAddress.getLocalHost();
-        int port = ((InetSocketAddress)listener.getLocalAddress()).getPort();
-        InetSocketAddress isa = new InetSocketAddress(lh, port);
-        ch.connect(isa).get();
-        try {
-            result.get();
-            throw new RuntimeException("Connection was accepted");
-        } catch (ExecutionException x) {
-            Throwable cause = x.getCause();
-            if (!(cause instanceof IOException))
-                throw new RuntimeException("Cause should be IOException");
-            cause = cause.getCause();
-            if (!(cause instanceof ShutdownChannelGroupException))
-                throw new RuntimeException("IOException cause should be ShutdownChannelGroupException");
-        }
-
-        // initiate another accept even though channel group is shutdown.
-        Future<AsynchronousSocketChannel> res = listener.accept();
-        try {
-            res.get(3, TimeUnit.SECONDS);
-            throw new RuntimeException("TimeoutException expected");
-        } catch (TimeoutException x) {
-        }
-        // connect to the listener which should cause the accept to complete
-        AsynchronousSocketChannel.open().connect(isa);
-        try {
-            res.get();
-            throw new RuntimeException("Connection was accepted");
-        } catch (ExecutionException x) {
-            Throwable cause = x.getCause();
-            if (!(cause instanceof IOException))
-                throw new RuntimeException("Cause should be IOException");
-            cause = cause.getCause();
-            if (!(cause instanceof ShutdownChannelGroupException))
-                throw new RuntimeException("IOException cause should be ShutdownChannelGroupException");
-        }
-
-        // group should *not* terminate as channels are open
-        boolean terminated = group.awaitTermination(3, TimeUnit.SECONDS);
-        if (terminated)
-            throw new RuntimeException("Group should not have terminated");
-
-        // close channel; group should terminate quickly
-        ch.close();
-        listener.close();
-        awaitTermination(group);
     }
 
     static void miscTests() throws Exception {
--- a/jdk/test/java/nio/channels/AsynchronousChannelGroup/GroupOfOne.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/test/java/nio/channels/AsynchronousChannelGroup/GroupOfOne.java	Mon Aug 29 08:53:32 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 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
@@ -41,34 +41,36 @@
 public class GroupOfOne {
 
     public static void main(String[] args) throws Exception {
+        final List<AsynchronousSocketChannel> accepted = new ArrayList<>();
+
         // create listener to accept connections
-        final AsynchronousServerSocketChannel listener =
-            AsynchronousServerSocketChannel.open()
-                .bind(new InetSocketAddress(0));
-        final List<AsynchronousSocketChannel> accepted = new ArrayList<AsynchronousSocketChannel>();
-        listener.accept((Void)null, new CompletionHandler<AsynchronousSocketChannel,Void>() {
-            public void completed(AsynchronousSocketChannel ch, Void att) {
-                synchronized (accepted) {
-                    accepted.add(ch);
+        try (final AsynchronousServerSocketChannel listener =
+                AsynchronousServerSocketChannel.open()) {
+
+            listener.bind(new InetSocketAddress(0));
+            listener.accept((Void)null, new CompletionHandler<AsynchronousSocketChannel,Void>() {
+                public void completed(AsynchronousSocketChannel ch, Void att) {
+                    synchronized (accepted) {
+                        accepted.add(ch);
+                    }
+                    listener.accept((Void)null, this);
                 }
-                listener.accept((Void)null, this);
-            }
-            public void failed(Throwable exc, Void att) {
-            }
-        });
+                public void failed(Throwable exc, Void att) {
+                }
+            });
 
-        int port = ((InetSocketAddress)(listener.getLocalAddress())).getPort();
-        SocketAddress sa = new InetSocketAddress(InetAddress.getLocalHost(), port);
+            int port = ((InetSocketAddress)(listener.getLocalAddress())).getPort();
+            SocketAddress sa = new InetSocketAddress(InetAddress.getLocalHost(), port);
 
-        test(sa, true, false);
-        test(sa, false, true);
-        test(sa, true, true);
-
-        // clean-up
-        listener.close();
-        synchronized (accepted) {
-            for (AsynchronousSocketChannel ch: accepted) {
-                ch.close();
+            test(sa, true, false);
+            test(sa, false, true);
+            test(sa, true, true);
+        } finally {
+            // clean-up
+            synchronized (accepted) {
+                for (AsynchronousSocketChannel ch: accepted) {
+                    ch.close();
+                }
             }
         }
     }
@@ -86,60 +88,60 @@
                     return new Thread(r);
                 }});
         final AsynchronousSocketChannel ch = AsynchronousSocketChannel.open(group);
+        try {
+            // the latch counts down when:
+            // 1. The read operation fails (expected)
+            // 2. the close/shutdown completes
+            final CountDownLatch latch = new CountDownLatch(2);
 
-        // the latch counts down when:
-        // 1. The read operation fails (expected)
-        // 2. the close/shutdown completes
-        final CountDownLatch latch = new CountDownLatch(2);
+            ch.connect(sa, (Void)null, new CompletionHandler<Void,Void>() {
+                public void completed(Void result, Void att)  {
+                    System.out.println("Connected");
 
-        ch.connect(sa, (Void)null, new CompletionHandler<Void,Void>() {
-            public void completed(Void result, Void att)  {
-                System.out.println("Connected");
+                    // initiate I/O operation that does not complete (successfully)
+                    ByteBuffer buf = ByteBuffer.allocate(100);
+                    ch.read(buf, (Void)null, new CompletionHandler<Integer,Void>() {
+                        public void completed(Integer bytesRead, Void att)  {
+                            throw new RuntimeException();
+                        }
+                        public void failed(Throwable exc, Void att) {
+                            if (!(exc instanceof AsynchronousCloseException))
+                                throw new RuntimeException(exc);
+                            System.out.println("Read failed (expected)");
+                            latch.countDown();
+                        }
+                    });
 
-                // initiate I/O operation that does not complete (successfully)
-                ByteBuffer buf = ByteBuffer.allocate(100);
-                ch.read(buf, (Void)null, new CompletionHandler<Integer,Void>() {
-                    public void completed(Integer bytesRead, Void att)  {
+                    // close channel or shutdown group
+                    try {
+                        if (closeChannel) {
+                            System.out.print("Close channel ...");
+                            ch.close();
+                            System.out.println(" done.");
+                        }
+                        if (shutdownGroup) {
+                            System.out.print("Shutdown group ...");
+                            group.shutdownNow();
+                            System.out.println(" done.");
+                        }
+                        latch.countDown();
+                    } catch (IOException e) {
                         throw new RuntimeException();
                     }
-                    public void failed(Throwable exc, Void att) {
-                        if (!(exc instanceof AsynchronousCloseException))
-                            throw new RuntimeException(exc);
-                        System.out.println("Read failed (expected)");
-                        latch.countDown();
-                    }
-                });
+                }
+                public void failed(Throwable exc, Void att) {
+                    throw new RuntimeException(exc);
+                }
+            });
 
-                // close channel or shutdown group
-                try {
-                    if (closeChannel) {
-                        System.out.print("Close channel ...");
-                        ch.close();
-                        System.out.println(" done.");
-                    }
-                    if (shutdownGroup) {
-                        System.out.print("Shutdown group ...");
-                        group.shutdownNow();
-                        System.out.println(" done.");
-                    }
-                    latch.countDown();
-                } catch (IOException e) {
-                    throw new RuntimeException();
-                }
-            }
-            public void failed(Throwable exc, Void att) {
-                throw new RuntimeException(exc);
-            }
-        });
-
-        latch.await();
-
-        // clean-up
-        group.shutdown();
-        boolean terminated = group.awaitTermination(20, TimeUnit.SECONDS);
-        if (!terminated)
-            throw new RuntimeException("Group did not terminate");
-
+            latch.await();
+        } finally {
+            // clean-up
+            group.shutdown();
+            boolean terminated = group.awaitTermination(20, TimeUnit.SECONDS);
+            if (!terminated)
+                throw new RuntimeException("Group did not terminate");
+        }
         System.out.println("TEST OKAY");
     }
 }
--- a/jdk/test/java/nio/channels/AsynchronousChannelGroup/Identity.java	Wed Jul 20 15:07:48 2016 +0200
+++ b/jdk/test/java/nio/channels/AsynchronousChannelGroup/Identity.java	Mon Aug 29 08:53:32 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 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
@@ -76,89 +76,91 @@
     }
 
     public static void main(String[] args) throws Exception {
-        // create listener to accept connections
-        final AsynchronousServerSocketChannel listener =
-            AsynchronousServerSocketChannel.open()
-                .bind(new InetSocketAddress(0));
-        listener.accept((Void)null, new CompletionHandler<AsynchronousSocketChannel,Void>() {
-            public void completed(final AsynchronousSocketChannel ch, Void att) {
-                listener.accept((Void)null, this);
-                final ByteBuffer buf = ByteBuffer.allocate(100);
-                ch.read(buf, ch, new CompletionHandler<Integer,AsynchronousSocketChannel>() {
-                    public void completed(Integer bytesRead, AsynchronousSocketChannel ch) {
-                        if (bytesRead < 0) {
-                            try { ch.close(); } catch (IOException ignore) { }
-                        } else {
-                            buf.clear();
-                            ch.read(buf, ch, this);
-                        }
-                    }
-                    public void failed(Throwable exc, AsynchronousSocketChannel ch) {
-                        try { ch.close(); } catch (IOException ignore) { }
-                    }
-                });
-            }
-            public void failed(Throwable exc, Void att) {
-            }
-        });
-        int port = ((InetSocketAddress)(listener.getLocalAddress())).getPort();
-        SocketAddress sa = new InetSocketAddress(InetAddress.getLocalHost(), port);
-
         // create 3-10 channels, each in its own group
         final int groupCount = 3 + rand.nextInt(8);
-        AsynchronousChannelGroup[] groups = new AsynchronousChannelGroup[groupCount];
+        final AsynchronousChannelGroup[] groups = new AsynchronousChannelGroup[groupCount];
         final AsynchronousSocketChannel[] channels = new AsynchronousSocketChannel[groupCount];
-        for (int i=0; i<groupCount; i++) {
-            ThreadFactory factory = createThreadFactory(i);
-            AsynchronousChannelGroup group;
-            if (rand.nextBoolean()) {
-                int nThreads = 1 + rand.nextInt(10);
-                group = AsynchronousChannelGroup.withFixedThreadPool(nThreads, factory);
-            } else {
-                ExecutorService pool = Executors.newCachedThreadPool(factory);
-                group = AsynchronousChannelGroup.withCachedThreadPool(pool, rand.nextInt(5));
+
+        // create listener to accept connections
+        try (final AsynchronousServerSocketChannel listener =
+                AsynchronousServerSocketChannel.open()) {
+
+            listener.bind(new InetSocketAddress(0));
+            listener.accept((Void)null, new CompletionHandler<AsynchronousSocketChannel,Void>() {
+                public void completed(final AsynchronousSocketChannel ch, Void att) {
+                    listener.accept((Void)null, this);
+                    final ByteBuffer buf = ByteBuffer.allocate(100);
+                    ch.read(buf, ch, new CompletionHandler<Integer,AsynchronousSocketChannel>() {
+                        public void completed(Integer bytesRead, AsynchronousSocketChannel ch) {
+                            if (bytesRead < 0) {
+                                try { ch.close(); } catch (IOException ignore) { }
+                            } else {
+                                buf.clear();
+                                ch.read(buf, ch, this);
+                            }
+                        }
+                        public void failed(Throwable exc, AsynchronousSocketChannel ch) {
+                            try { ch.close(); } catch (IOException ignore) { }
+                        }
+                    });
+                }
+                public void failed(Throwable exc, Void att) {
+                }
+            });
+            int port = ((InetSocketAddress)(listener.getLocalAddress())).getPort();
+            SocketAddress sa = new InetSocketAddress(InetAddress.getLocalHost(), port);
+
+            for (int i=0; i<groupCount; i++) {
+                ThreadFactory factory = createThreadFactory(i);
+                AsynchronousChannelGroup group;
+                if (rand.nextBoolean()) {
+                    int nThreads = 1 + rand.nextInt(10);
+                    group = AsynchronousChannelGroup.withFixedThreadPool(nThreads, factory);
+                } else {
+                    ExecutorService pool = Executors.newCachedThreadPool(factory);
+                    group = AsynchronousChannelGroup.withCachedThreadPool(pool, rand.nextInt(5));
+                }
+                groups[i] = group;
+
+                // create channel in group and connect it to the server
+                AsynchronousSocketChannel ch = AsynchronousSocketChannel.open(group);
+                ch.connect(sa).get();
+                channels[i] = ch;
             }
-            groups[i] = group;
 
-            // create channel in group and connect it to the server
-            AsynchronousSocketChannel ch = AsynchronousSocketChannel.open(group);
-            ch.connect(sa).get();
-            channels[i] = ch;
+            // randomly write to each channel, ensuring that the completion handler
+            // is always invoked by a thread with the right identity.
+            final AtomicInteger writeCount = new AtomicInteger(100);
+            channels[0].write(getBuffer(), 0, new CompletionHandler<Integer,Integer>() {
+                public void completed(Integer bytesWritten, Integer groupId) {
+                    if (bytesWritten != 1)
+                        fail("Expected 1 byte to be written");
+                    if (!myGroup.get().equals(groupId))
+                        fail("Handler invoked by thread with the wrong identity");
+                    if (writeCount.decrementAndGet() > 0) {
+                        int id = rand.nextInt(groupCount);
+                        channels[id].write(getBuffer(), id, this);
+                    } else {
+                        done.countDown();
+                    }
+                }
+                public void failed(Throwable exc, Integer groupId) {
+                    fail(exc.getMessage());
+                }
+            });
+
+            // wait until done
+            done.await();
+