Merge
authorprr
Fri, 19 Jan 2018 09:32:10 -0800
changeset 48648 371c6d66d2ec
parent 48647 e4b03365ddbf (current diff)
parent 48638 01094f78d990 (diff)
child 48649 6a014a1e8d2b
child 48725 9f728dd46c56
Merge
src/java.xml/share/classes/com/sun/org/apache/xalan/internal/utils/FactoryImpl.java
--- a/.hgtags	Thu Jan 18 11:22:28 2018 +0530
+++ b/.hgtags	Fri Jan 19 09:32:10 2018 -0800
@@ -465,3 +465,4 @@
 4f830b447edf04fb4a52151a5ad44d9bb60723cd jdk-10+37
 e569e83139fdfbecfeb3cd9014d560917787f158 jdk-10+38
 5b834ec962366e00d4445352a999a3ac14e26f64 jdk-10+39
+860326263d1f6a83996d7da0f4c66806ae4aa1eb jdk-10+40
--- a/make/autoconf/generated-configure.sh	Thu Jan 18 11:22:28 2018 +0530
+++ b/make/autoconf/generated-configure.sh	Fri Jan 19 09:32:10 2018 -0800
@@ -902,6 +902,9 @@
 VERSION_UPDATE
 VERSION_INTERIM
 VERSION_FEATURE
+VENDOR_URL_VM_BUG
+VENDOR_URL_BUG
+VENDOR_URL
 COMPANY_NAME
 MACOSX_BUNDLE_ID_BASE
 MACOSX_BUNDLE_NAME_BASE
@@ -1150,6 +1153,9 @@
 with_version_minor
 with_version_security
 with_vendor_name
+with_vendor_url
+with_vendor_bug_url
+with_vendor_vm_bug_url
 with_version_string
 with_version_pre
 with_version_opt
@@ -2074,7 +2080,16 @@
                           compatibility and is ignored
   --with-version-security Deprecated. Option is kept for backwards
                           compatibility and is ignored
-  --with-vendor-name      Set vendor name [not specified]
+  --with-vendor-name      Set vendor name. Among others, used to set the
+                          'java.vendor' and 'java.vm.vendor' system
+                          properties. [not specified]
+  --with-vendor-url       Set the 'java.vendor.url' system property [not
+                          specified]
+  --with-vendor-bug-url   Set the 'java.vendor.url.bug' system property [not
+                          specified]
+  --with-vendor-vm-bug-url
+                          Sets the bug URL which will be displayed when the VM
+                          crashes [not specified]
   --with-version-string   Set version string [calculated]
   --with-version-pre      Set the base part of the version 'PRE' field
                           (pre-release identifier) ['internal']
@@ -5176,7 +5191,7 @@
 #CUSTOM_AUTOCONF_INCLUDE
 
 # Do not change or remove the following line, it is needed for consistency checks:
-DATE_WHEN_GENERATED=1513805283
+DATE_WHEN_GENERATED=1516225089
 
 ###############################################################################
 #
@@ -25072,12 +25087,62 @@
   if test "x$with_vendor_name" = xyes; then
     as_fn_error $? "--with-vendor-name must have a value" "$LINENO" 5
   elif  ! [[ $with_vendor_name =~ ^[[:print:]]*$ ]] ; then
-    as_fn_error $? "--with--vendor-name contains non-printing characters: $with_vendor_name" "$LINENO" 5
-  else
+    as_fn_error $? "--with-vendor-name contains non-printing characters: $with_vendor_name" "$LINENO" 5
+  elif test "x$with_vendor_name" != x; then
+    # Only set COMPANY_NAME if '--with-vendor-name' was used and is not empty.
+    # Otherwise we will use the value from "version-numbers" included above.
     COMPANY_NAME="$with_vendor_name"
   fi
 
 
+  # The vendor URL, if any
+
+# Check whether --with-vendor-url was given.
+if test "${with_vendor_url+set}" = set; then :
+  withval=$with_vendor_url;
+fi
+
+  if test "x$with_vendor_url" = xyes; then
+    as_fn_error $? "--with-vendor-url must have a value" "$LINENO" 5
+  elif  ! [[ $with_vendor_url =~ ^[[:print:]]*$ ]] ; then
+    as_fn_error $? "--with-vendor-url contains non-printing characters: $with_vendor_url" "$LINENO" 5
+  else
+    VENDOR_URL="$with_vendor_url"
+  fi
+
+
+  # The vendor bug URL, if any
+
+# Check whether --with-vendor-bug-url was given.
+if test "${with_vendor_bug_url+set}" = set; then :
+  withval=$with_vendor_bug_url;
+fi
+
+  if test "x$with_vendor_bug_url" = xyes; then
+    as_fn_error $? "--with-vendor-bug-url must have a value" "$LINENO" 5
+  elif  ! [[ $with_vendor_bug_url =~ ^[[:print:]]*$ ]] ; then
+    as_fn_error $? "--with-vendor-bug-url contains non-printing characters: $with_vendor_bug_url" "$LINENO" 5
+  else
+    VENDOR_URL_BUG="$with_vendor_bug_url"
+  fi
+
+
+  # The vendor VM bug URL, if any
+
+# Check whether --with-vendor-vm-bug-url was given.
+if test "${with_vendor_vm_bug_url+set}" = set; then :
+  withval=$with_vendor_vm_bug_url;
+fi
+
+  if test "x$with_vendor_vm_bug_url" = xyes; then
+    as_fn_error $? "--with-vendor-vm-bug-url must have a value" "$LINENO" 5
+  elif  ! [[ $with_vendor_vm_bug_url =~ ^[[:print:]]*$ ]] ; then
+    as_fn_error $? "--with-vendor-vm-bug-url contains non-printing characters: $with_vendor_vm_bug_url" "$LINENO" 5
+  else
+    VENDOR_URL_VM_BUG="$with_vendor_vm_bug_url"
+  fi
+
+
   # Override version from arguments
 
   # If --with-version-string is set, process it first. It is possible to
--- a/make/autoconf/jdk-version.m4	Thu Jan 18 11:22:28 2018 +0530
+++ b/make/autoconf/jdk-version.m4	Fri Jan 19 09:32:10 2018 -0800
@@ -80,16 +80,55 @@
 
   # The vendor name, if any
   AC_ARG_WITH(vendor-name, [AS_HELP_STRING([--with-vendor-name],
-      [Set vendor name @<:@not specified@:>@])])
+      [Set vendor name. Among others, used to set the 'java.vendor'
+       and 'java.vm.vendor' system properties. @<:@not specified@:>@])])
   if test "x$with_vendor_name" = xyes; then
     AC_MSG_ERROR([--with-vendor-name must have a value])
   elif [ ! [[ $with_vendor_name =~ ^[[:print:]]*$ ]] ]; then
-    AC_MSG_ERROR([--with--vendor-name contains non-printing characters: $with_vendor_name])
-  else
+    AC_MSG_ERROR([--with-vendor-name contains non-printing characters: $with_vendor_name])
+  elif test "x$with_vendor_name" != x; then
+    # Only set COMPANY_NAME if '--with-vendor-name' was used and is not empty.
+    # Otherwise we will use the value from "version-numbers" included above.
     COMPANY_NAME="$with_vendor_name"
   fi
   AC_SUBST(COMPANY_NAME)
 
+  # The vendor URL, if any
+  AC_ARG_WITH(vendor-url, [AS_HELP_STRING([--with-vendor-url],
+      [Set the 'java.vendor.url' system property @<:@not specified@:>@])])
+  if test "x$with_vendor_url" = xyes; then
+    AC_MSG_ERROR([--with-vendor-url must have a value])
+  elif [ ! [[ $with_vendor_url =~ ^[[:print:]]*$ ]] ]; then
+    AC_MSG_ERROR([--with-vendor-url contains non-printing characters: $with_vendor_url])
+  else
+    VENDOR_URL="$with_vendor_url"
+  fi
+  AC_SUBST(VENDOR_URL)
+
+  # The vendor bug URL, if any
+  AC_ARG_WITH(vendor-bug-url, [AS_HELP_STRING([--with-vendor-bug-url],
+      [Set the 'java.vendor.url.bug' system property @<:@not specified@:>@])])
+  if test "x$with_vendor_bug_url" = xyes; then
+    AC_MSG_ERROR([--with-vendor-bug-url must have a value])
+  elif [ ! [[ $with_vendor_bug_url =~ ^[[:print:]]*$ ]] ]; then
+    AC_MSG_ERROR([--with-vendor-bug-url contains non-printing characters: $with_vendor_bug_url])
+  else
+    VENDOR_URL_BUG="$with_vendor_bug_url"
+  fi
+  AC_SUBST(VENDOR_URL_BUG)
+
+  # The vendor VM bug URL, if any
+  AC_ARG_WITH(vendor-vm-bug-url, [AS_HELP_STRING([--with-vendor-vm-bug-url],
+      [Sets the bug URL which will be displayed when the VM crashes @<:@not specified@:>@])])
+  if test "x$with_vendor_vm_bug_url" = xyes; then
+    AC_MSG_ERROR([--with-vendor-vm-bug-url must have a value])
+  elif [ ! [[ $with_vendor_vm_bug_url =~ ^[[:print:]]*$ ]] ]; then
+    AC_MSG_ERROR([--with-vendor-vm-bug-url contains non-printing characters: $with_vendor_vm_bug_url])
+  else
+    VENDOR_URL_VM_BUG="$with_vendor_vm_bug_url"
+  fi
+  AC_SUBST(VENDOR_URL_VM_BUG)
+
   # Override version from arguments
 
   # If --with-version-string is set, process it first. It is possible to
--- a/make/autoconf/spec.gmk.in	Thu Jan 18 11:22:28 2018 +0530
+++ b/make/autoconf/spec.gmk.in	Fri Jan 19 09:32:10 2018 -0800
@@ -142,6 +142,20 @@
 
 COPYRIGHT_YEAR:=@COPYRIGHT_YEAR@
 
+# Platform naming variables
+LAUNCHER_NAME:=@LAUNCHER_NAME@
+PRODUCT_NAME:=@PRODUCT_NAME@
+PRODUCT_SUFFIX:=@PRODUCT_SUFFIX@
+JDK_RC_PLATFORM_NAME:=@JDK_RC_PLATFORM_NAME@
+COMPANY_NAME:=@COMPANY_NAME@
+HOTSPOT_VM_DISTRO:=@HOTSPOT_VM_DISTRO@
+MACOSX_BUNDLE_NAME_BASE=@MACOSX_BUNDLE_NAME_BASE@
+MACOSX_BUNDLE_ID_BASE=@MACOSX_BUNDLE_ID_BASE@
+USERNAME:=@USERNAME@
+VENDOR_URL:=@VENDOR_URL@
+VENDOR_URL_BUG:=@VENDOR_URL_BUG@
+VENDOR_URL_VM_BUG:=@VENDOR_URL_VM_BUG@
+
 # New (JEP-223) version information
 
 ## Building blocks of the version string
@@ -201,16 +215,30 @@
     -DVERSION_CLASSFILE_MINOR=$(VERSION_CLASSFILE_MINOR) \
     #
 
-# Platform naming variables
-LAUNCHER_NAME:=@LAUNCHER_NAME@
-PRODUCT_NAME:=@PRODUCT_NAME@
-PRODUCT_SUFFIX:=@PRODUCT_SUFFIX@
-JDK_RC_PLATFORM_NAME:=@JDK_RC_PLATFORM_NAME@
-COMPANY_NAME:=@COMPANY_NAME@
-HOTSPOT_VM_DISTRO:=@HOTSPOT_VM_DISTRO@
-MACOSX_BUNDLE_NAME_BASE=@MACOSX_BUNDLE_NAME_BASE@
-MACOSX_BUNDLE_ID_BASE=@MACOSX_BUNDLE_ID_BASE@
-USERNAME:=@USERNAME@
+ifneq ($(COMPANY_NAME),)
+  # COMPANY_NAME is set to "N/A" in $AUTOCONF_DIR/version-numbers by default,
+  # but can be customized with the '--with-vendor-name' configure option.
+  # Only export "VENDOR" to the build if COMPANY_NAME contains a real value.
+  # Otherwise the default value for VENDOR, which is used to set the "java.vendor"
+  # and "java.vm.vendor" properties is hard-coded into the source code (i.e. in
+  # System.c in the jdk for "vm.vendor" and vm_version.cpp in the VM for "java.vm.vendor") 
+  ifneq ($(COMPANY_NAME), N/A)
+    VERSION_CFLAGS += -DVENDOR='"$(COMPANY_NAME)"' 
+  endif
+endif
+
+# Only export VENDOR_URL, VENDOR_URL_BUG and VENDOR_VM_URL_BUG to the build if
+# they are not empty. Otherwise, default values which are defined in the sources
+# will be used.
+ifneq ($(VENDOR_URL),)
+  VERSION_CFLAGS += -DVENDOR_URL='"$(VENDOR_URL)"'
+endif
+ifneq ($(VENDOR_URL_BUG),)
+  VERSION_CFLAGS += -DVENDOR_URL_BUG='"$(VENDOR_URL_BUG)"'
+endif
+ifneq ($(VENDOR_URL_VM_BUG),)
+  VERSION_CFLAGS += -DVENDOR_URL_VM_BUG='"$(VENDOR_URL_VM_BUG)"'
+endif
 
 # Different naming strings generated from the above information.
 RUNTIME_NAME=$(PRODUCT_NAME) $(PRODUCT_SUFFIX)
--- a/make/data/jdwp/jdwp.spec	Thu Jan 18 11:22:28 2018 +0530
+++ b/make/data/jdwp/jdwp.spec	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2018, 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
@@ -869,7 +869,6 @@
         "section in "
         "<cite>The Java&trade; Virtual Machine Specification</cite>. "
         "Since JDWP version 1.5."
-        "<p>
         (Out
             (referenceType refType "The reference type ID.")
         )
@@ -2723,7 +2722,6 @@
         "<P>"
         "The events that are grouped in a composite event are restricted in the "
         "following ways: "
-        "<P>"
         "<UL>"
         "<LI>Only with other thread start events for the same thread:"
         "    <UL>"
--- a/make/hotspot/lib/CompileJvm.gmk	Thu Jan 18 11:22:28 2018 +0530
+++ b/make/hotspot/lib/CompileJvm.gmk	Fri Jan 19 09:32:10 2018 -0800
@@ -222,6 +222,7 @@
     CFLAGS_DEBUG_SYMBOLS := $(JVM_CFLAGS_SYMBOLS), \
     CXXFLAGS_DEBUG_SYMBOLS := $(JVM_CFLAGS_SYMBOLS), \
     vm_version.cpp_CXXFLAGS := $(CFLAGS_VM_VERSION), \
+    arguments.cpp_CXXFLAGS := $(CFLAGS_VM_VERSION), \
     DISABLED_WARNINGS_clang := tautological-compare, \
     DISABLED_WARNINGS_xlc := 1540-0216 1540-0198 1540-1090 1540-1639 \
         1540-1088 1500-010, \
--- a/make/jdk/src/classes/build/tools/jdwpgen/AbstractCommandNode.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/make/jdk/src/classes/build/tools/jdwpgen/AbstractCommandNode.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2018, 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
@@ -30,8 +30,8 @@
 class AbstractCommandNode extends AbstractNamedNode {
 
     void document(PrintWriter writer) {
-        writer.println("<h5><a name=\"" + context.whereC + "\">" + name +
-                       " Command</a> (" + nameNode.value() + ")</h5>");
+        writer.println("<h5 id=\"" + context.whereC + "\">" + name +
+                       " Command (" + nameNode.value() + ")</h5>");
         writer.println(comment());
         writer.println("<dl>");
         for (Node node : components) {
--- a/make/jdk/src/classes/build/tools/jdwpgen/AbstractNamedNode.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/make/jdk/src/classes/build/tools/jdwpgen/AbstractNamedNode.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2018, 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
@@ -62,8 +62,8 @@
     }
 
     void document(PrintWriter writer) {
-        writer.println("<h4><a name=" + name + ">" + name +
-                       " Command Set</a></h4>");
+        writer.println("<h4 id=\"" + name + "\">" + name +
+                       " Command Set</h4>");
         for (Node node : components) {
             node.document(writer);
         }
--- a/make/jdk/src/classes/build/tools/jdwpgen/AbstractTypeListNode.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/make/jdk/src/classes/build/tools/jdwpgen/AbstractTypeListNode.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2018, 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
@@ -43,11 +43,11 @@
         if (components.isEmpty()) {
             writer.println("<dd>(None)");
         } else {
-            writer.println("<dd><table border=1 cellpadding=3 cellspacing=0 width=\"90%\" summary=\"\"><tr>");
+            writer.println("<dd><table><tr>");
             for (int i = maxStructIndent; i > 0; --i) {
-                writer.print("<th width=\"4%\">");
+                writer.print("<th style=\"width: 4%\">");
             }
-            writer.println("<th width=\"15%\"><th width=\"65%\">");
+            writer.println("<th style=\"width: 15%\"><th style=\"width: 65%\">");
             writer.println("");
             for (Node node : components) {
                 node.document(writer);
--- a/make/jdk/src/classes/build/tools/jdwpgen/CommandSetNode.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/make/jdk/src/classes/build/tools/jdwpgen/CommandSetNode.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2018, 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,8 @@
     }
 
     void document(PrintWriter writer) {
-        writer.println("<h4><a name=\"" + context.whereC + "\">" + name +
-                       " Command Set</a> (" +
+        writer.println("<h4 id=\"" + context.whereC + "\">" + name +
+                       " Command Set (" +
                        nameNode.value() + ")</h4>");
         writer.println(comment());
         for (Node node : components) {
@@ -51,11 +51,13 @@
         writer.print("<li><a href=\"#" + context.whereC + "\">");
         writer.println(name() + "</a> Command Set (" +
                        nameNode.value() + ")");
-        writer.println("<ul>");
-        for (Node node : components) {
-            node.documentIndex(writer);
+        if (components.size() > 0) {
+            writer.println("<ul>");
+            for (Node node : components) {
+                node.documentIndex(writer);
+            }
+            writer.println("</ul>");
         }
-        writer.println("</ul>");
     }
 
     void genJavaClassSpecifics(PrintWriter writer, int depth) {
--- a/make/jdk/src/classes/build/tools/jdwpgen/ConstantSetNode.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/make/jdk/src/classes/build/tools/jdwpgen/ConstantSetNode.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2018, 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
@@ -54,15 +54,15 @@
     }
 
     void document(PrintWriter writer) {
-        writer.println("<h4><a name=\"" + context.whereC + "\">" + name +
-                       " Constants</a></h4>");
+        writer.println("<h4 id=\"" + context.whereC + "\">" + name +
+                       " Constants</h4>");
         writer.println(comment());
-        writer.println("<dd><table border=1 cellpadding=3 cellspacing=0 width=\"90%\" summary=\"\"><tr>");
-        writer.println("<th width=\"20%\"><th width=\"5%\"><th width=\"65%\">");
+        writer.println("<table><tr>");
+        writer.println("<th style=\"width: 20%\"><th style=\"width: 5%\"><th style=\"width:  65%\">");
         ConstantNode n;
         for (Node node : components) {
             n = (ConstantNode)node;
-            writer.println("<a NAME=\"" + name + "_" + n.name + "\"></a>");
+            writer.println("<span id=\"" + name + "_" + n.name + "\"></span>");
             n.document(writer);
         }
         writer.println("</table>");
--- a/make/jdk/src/classes/build/tools/jdwpgen/ErrorSetNode.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/make/jdk/src/classes/build/tools/jdwpgen/ErrorSetNode.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2018, 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
@@ -43,7 +43,7 @@
         if (components.isEmpty()) {
             writer.println("<dd>(None)");
         } else {
-            writer.println("<dd><table border=1 cellpadding=3 cellspacing=0 width=\"90%\" summary=\"\">");
+            writer.println("<dd><table>");
         for (Node node : components) {
             node.document(writer);
         }
--- a/make/jdk/src/classes/build/tools/jdwpgen/RootNode.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/make/jdk/src/classes/build/tools/jdwpgen/RootNode.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2018, 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,11 +41,22 @@
 
     void document(PrintWriter writer) {
         writer.println("<!DOCTYPE html>");
-        writer.println("<html><head><title>" + comment() + "</title></head>");
-        writer.println("<body bgcolor=\"white\">");
+        writer.println("<html lang=\"en\">");
+        writer.println("<head>");
+        writer.println("<meta charset=\"utf-8\"/>");
+        writer.println("<title>" + comment() + "</title>");
+        writer.println("<style>");
+        writer.println("body {background-color:white;}");
+        writer.println("table {border: 1px solid grey; border-spacing:0px; border-collapse: separate; width: 90%;}");
+        writer.println("td, th {padding: 3px; border: 1px solid black;}");
+        writer.println("</style>");
+        writer.println("</head>");
+        writer.println("<body>");
+        writer.println("<ul>");
         for (Node node : components) {
             node.documentIndex(writer);
         }
+        writer.println("</ul>");
         for (Node node : components) {
             node.document(writer);
         }
--- a/make/test/JtregNativeHotspot.gmk	Thu Jan 18 11:22:28 2018 +0530
+++ b/make/test/JtregNativeHotspot.gmk	Fri Jan 19 09:32:10 2018 -0800
@@ -44,6 +44,7 @@
 # Add more directories here when needed.
 BUILD_HOTSPOT_JTREG_NATIVE_SRC += \
     $(TOPDIR)/test/hotspot/jtreg/gc/g1/TestJNIWeakG1 \
+    $(TOPDIR)/test/hotspot/jtreg/gc/stress/TestJNIBlockFullGC \
     $(TOPDIR)/test/hotspot/jtreg/gc/stress/gclocker \
     $(TOPDIR)/test/hotspot/jtreg/gc/cslocker \
     $(TOPDIR)/test/hotspot/jtreg/native_sanity \
--- a/src/hotspot/cpu/aarch64/assembler_aarch64.hpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/cpu/aarch64/assembler_aarch64.hpp	Fri Jan 19 09:32:10 2018 -0800
@@ -2295,23 +2295,32 @@
     rf(Vn, 5), rf(Rd, 0);
   }
 
-#define INSN(NAME, opc, opc2)                                           \
+#define INSN(NAME, opc, opc2, isSHR)                                    \
   void NAME(FloatRegister Vd, SIMD_Arrangement T, FloatRegister Vn, int shift){ \
     starti;                                                             \
-    /* The encodings for the immh:immb fields (bits 22:16) are          \
-     *   0001 xxx       8B/16B, shift = xxx                             \
-     *   001x xxx       4H/8H,  shift = xxxx                            \
-     *   01xx xxx       2S/4S,  shift = xxxxx                           \
-     *   1xxx xxx       1D/2D,  shift = xxxxxx (1D is RESERVED)         \
+    /* The encodings for the immh:immb fields (bits 22:16) in *SHR are  \
+     *   0001 xxx       8B/16B, shift = 16  - UInt(immh:immb)           \
+     *   001x xxx       4H/8H,  shift = 32  - UInt(immh:immb)           \
+     *   01xx xxx       2S/4S,  shift = 64  - UInt(immh:immb)           \
+     *   1xxx xxx       1D/2D,  shift = 128 - UInt(immh:immb)           \
+     *   (1D is RESERVED)                                               \
+     * for SHL shift is calculated as:                                  \
+     *   0001 xxx       8B/16B, shift = UInt(immh:immb) - 8             \
+     *   001x xxx       4H/8H,  shift = UInt(immh:immb) - 16            \
+     *   01xx xxx       2S/4S,  shift = UInt(immh:immb) - 32            \
+     *   1xxx xxx       1D/2D,  shift = UInt(immh:immb) - 64            \
+     *   (1D is RESERVED)                                               \
      */                                                                 \
     assert((1 << ((T>>1)+3)) > shift, "Invalid Shift value");           \
+    int cVal = (1 << (((T >> 1) + 3) + (isSHR ? 1 : 0)));               \
+    int encodedShift = isSHR ? cVal - shift : cVal + shift;             \
     f(0, 31), f(T & 1, 30), f(opc, 29), f(0b011110, 28, 23),            \
-    f((1 << ((T>>1)+3))|shift, 22, 16); f(opc2, 15, 10), rf(Vn, 5), rf(Vd, 0); \
+    f(encodedShift, 22, 16); f(opc2, 15, 10), rf(Vn, 5), rf(Vd, 0);     \
   }
 
-  INSN(shl,  0, 0b010101);
-  INSN(sshr, 0, 0b000001);
-  INSN(ushr, 1, 0b000001);
+  INSN(shl,  0, 0b010101, /* isSHR = */ false);
+  INSN(sshr, 0, 0b000001, /* isSHR = */ true);
+  INSN(ushr, 1, 0b000001, /* isSHR = */ true);
 
 #undef INSN
 
--- a/src/hotspot/cpu/aarch64/sharedRuntime_aarch64.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/cpu/aarch64/sharedRuntime_aarch64.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -774,7 +774,7 @@
     __ load_klass(rscratch1, receiver);
     __ ldr(tmp, Address(holder, CompiledICHolder::holder_klass_offset()));
     __ cmp(rscratch1, tmp);
-    __ ldr(rmethod, Address(holder, CompiledICHolder::holder_method_offset()));
+    __ ldr(rmethod, Address(holder, CompiledICHolder::holder_metadata_offset()));
     __ br(Assembler::EQ, ok);
     __ far_jump(RuntimeAddress(SharedRuntime::get_ic_miss_stub()));
 
--- a/src/hotspot/cpu/arm/macroAssembler_arm.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/cpu/arm/macroAssembler_arm.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -2475,49 +2475,65 @@
 // On success, the result will be in method_result, and execution falls through.
 // On failure, execution transfers to the given label.
 void MacroAssembler::lookup_interface_method(Register Rklass,
-                                             Register Rinterf,
-                                             Register Rindex,
+                                             Register Rintf,
+                                             RegisterOrConstant itable_index,
                                              Register method_result,
-                                             Register temp_reg1,
-                                             Register temp_reg2,
+                                             Register Rscan,
+                                             Register Rtmp,
                                              Label& L_no_such_interface) {
 
-  assert_different_registers(Rklass, Rinterf, temp_reg1, temp_reg2, Rindex);
-
-  Register Ritable = temp_reg1;
+  assert_different_registers(Rklass, Rintf, Rscan, Rtmp);
+
+  const int entry_size = itableOffsetEntry::size() * HeapWordSize;
+  assert(itableOffsetEntry::interface_offset_in_bytes() == 0, "not added for convenience");
 
   // Compute start of first itableOffsetEntry (which is at the end of the vtable)
   const int base = in_bytes(Klass::vtable_start_offset());
   const int scale = exact_log2(vtableEntry::size_in_bytes());
-  ldr_s32(temp_reg2, Address(Rklass, Klass::vtable_length_offset())); // Get length of vtable
-  add(Ritable, Rklass, base);
-  add(Ritable, Ritable, AsmOperand(temp_reg2, lsl, scale));
-
-  Label entry, search;
-
-  b(entry);
-
-  bind(search);
-  add(Ritable, Ritable, itableOffsetEntry::size() * HeapWordSize);
-
-  bind(entry);
-
-  // Check that the entry is non-null.  A null entry means that the receiver
-  // class doesn't implement the interface, and wasn't the same as the
-  // receiver class checked when the interface was resolved.
-
-  ldr(temp_reg2, Address(Ritable, itableOffsetEntry::interface_offset_in_bytes()));
-  cbz(temp_reg2, L_no_such_interface);
-
-  cmp(Rinterf, temp_reg2);
-  b(search, ne);
-
-  ldr_s32(temp_reg2, Address(Ritable, itableOffsetEntry::offset_offset_in_bytes()));
-  add(temp_reg2, temp_reg2, Rklass); // Add offset to Klass*
-  assert(itableMethodEntry::size() * HeapWordSize == wordSize, "adjust the scaling in the code below");
-  assert(itableMethodEntry::method_offset_in_bytes() == 0, "adjust the offset in the code below");
-
-  ldr(method_result, Address::indexed_ptr(temp_reg2, Rindex));
+  ldr_s32(Rtmp, Address(Rklass, Klass::vtable_length_offset())); // Get length of vtable
+  add(Rscan, Rklass, base);
+  add(Rscan, Rscan, AsmOperand(Rtmp, lsl, scale));
+
+  // Search through the itable for an interface equal to incoming Rintf
+  // itable looks like [intface][offset][intface][offset][intface][offset]
+
+  Label loop;
+  bind(loop);
+  ldr(Rtmp, Address(Rscan, entry_size, post_indexed));
+#ifdef AARCH64
+  Label found;
+  cmp(Rtmp, Rintf);
+  b(found, eq);
+  cbnz(Rtmp, loop);
+#else
+  cmp(Rtmp, Rintf);  // set ZF and CF if interface is found
+  cmn(Rtmp, 0, ne);  // check if tmp == 0 and clear CF if it is
+  b(loop, ne);
+#endif // AARCH64
+
+#ifdef AARCH64
+  b(L_no_such_interface);
+  bind(found);
+#else
+  // CF == 0 means we reached the end of itable without finding icklass
+  b(L_no_such_interface, cc);
+#endif // !AARCH64
+
+  if (method_result != noreg) {
+    // Interface found at previous position of Rscan, now load the method
+    ldr_s32(Rtmp, Address(Rscan, itableOffsetEntry::offset_offset_in_bytes() - entry_size));
+    if (itable_index.is_register()) {
+      add(Rtmp, Rtmp, Rklass); // Add offset to Klass*
+      assert(itableMethodEntry::size() * HeapWordSize == wordSize, "adjust the scaling in the code below");
+      assert(itableMethodEntry::method_offset_in_bytes() == 0, "adjust the offset in the code below");
+      ldr(method_result, Address::indexed_ptr(Rtmp, itable_index.as_register()));
+    } else {
+      int method_offset = itableMethodEntry::size() * HeapWordSize * itable_index.as_constant() +
+                          itableMethodEntry::method_offset_in_bytes();
+      add_slow(method_result, Rklass, method_offset);
+      ldr(method_result, Address(method_result, Rtmp));
+    }
+  }
 }
 
 #ifdef COMPILER2
--- a/src/hotspot/cpu/arm/macroAssembler_arm.hpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/cpu/arm/macroAssembler_arm.hpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1316,7 +1316,7 @@
 
   void lookup_interface_method(Register recv_klass,
                                Register intf_klass,
-                               Register itable_index,
+                               RegisterOrConstant itable_index,
                                Register method_result,
                                Register temp_reg1,
                                Register temp_reg2,
--- a/src/hotspot/cpu/arm/sharedRuntime_arm.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/cpu/arm/sharedRuntime_arm.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -984,7 +984,7 @@
 
   __ load_klass(receiver_klass, receiver);
   __ ldr(holder_klass, Address(Ricklass, CompiledICHolder::holder_klass_offset()));
-  __ ldr(Rmethod, Address(Ricklass, CompiledICHolder::holder_method_offset()));
+  __ ldr(Rmethod, Address(Ricklass, CompiledICHolder::holder_metadata_offset()));
   __ cmp(receiver_klass, holder_klass);
 
 #ifdef AARCH64
--- a/src/hotspot/cpu/arm/templateTable_arm.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/cpu/arm/templateTable_arm.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -4198,7 +4198,7 @@
   const Register Rflags  = R3_tmp;
   const Register Rklass  = R3_tmp;
 
-  prepare_invoke(byte_no, Rinterf, Rindex, Rrecv, Rflags);
+  prepare_invoke(byte_no, Rinterf, Rmethod, Rrecv, Rflags);
 
   // Special case of invokeinterface called for virtual method of
   // java.lang.Object.  See cpCacheOop.cpp for details.
@@ -4207,56 +4207,39 @@
   Label notMethod;
   __ tbz(Rflags, ConstantPoolCacheEntry::is_forced_virtual_shift, notMethod);
 
-  __ mov(Rmethod, Rindex);
   invokevirtual_helper(Rmethod, Rrecv, Rflags);
   __ bind(notMethod);
 
   // Get receiver klass into Rklass - also a null check
   __ load_klass(Rklass, Rrecv);
 
+  Label no_such_interface;
+
+  // Receiver subtype check against REFC.
+  __ lookup_interface_method(// inputs: rec. class, interface
+                             Rklass, Rinterf, noreg,
+                             // outputs:  scan temp. reg1, scan temp. reg2
+                             noreg, Ritable, Rtemp,
+                             no_such_interface);
+
   // profile this call
   __ profile_virtual_call(R0_tmp, Rklass);
 
-  // Compute start of first itableOffsetEntry (which is at the end of the vtable)
-  const int base = in_bytes(Klass::vtable_start_offset());
-  assert(vtableEntry::size() == 1, "adjust the scaling in the code below");
-  __ ldr_s32(Rtemp, Address(Rklass, Klass::vtable_length_offset())); // Get length of vtable
-  __ add(Ritable, Rklass, base);
-  __ add(Ritable, Ritable, AsmOperand(Rtemp, lsl, LogBytesPerWord));
-
-  Label entry, search, interface_ok;
-
-  __ b(entry);
-
-  __ bind(search);
-  __ add(Ritable, Ritable, itableOffsetEntry::size() * HeapWordSize);
-
-  __ bind(entry);
-
-  // Check that the entry is non-null.  A null entry means that the receiver
-  // class doesn't implement the interface, and wasn't the same as the
-  // receiver class checked when the interface was resolved.
-
-  __ ldr(Rtemp, Address(Ritable, itableOffsetEntry::interface_offset_in_bytes()));
-  __ cbnz(Rtemp, interface_ok);
-
-  // throw exception
-  __ call_VM(noreg, CAST_FROM_FN_PTR(address,
-                   InterpreterRuntime::throw_IncompatibleClassChangeError));
-
-  // the call_VM checks for exception, so we should never return here.
-  __ should_not_reach_here();
-
-  __ bind(interface_ok);
-
-  __ cmp(Rinterf, Rtemp);
-  __ b(search, ne);
-
-  __ ldr_s32(Rtemp, Address(Ritable, itableOffsetEntry::offset_offset_in_bytes()));
-  __ add(Rtemp, Rtemp, Rklass); // Add offset to Klass*
-  assert(itableMethodEntry::size() == 1, "adjust the scaling in the code below");
-
-  __ ldr(Rmethod, Address::indexed_ptr(Rtemp, Rindex));
+  // Get declaring interface class from method
+  __ ldr(Rtemp, Address(Rmethod, Method::const_offset()));
+  __ ldr(Rtemp, Address(Rtemp, ConstMethod::constants_offset()));
+  __ ldr(Rinterf, Address(Rtemp, ConstantPool::pool_holder_offset_in_bytes()));
+
+  // Get itable index from method
+  __ ldr_s32(Rtemp, Address(Rmethod, Method::itable_index_offset()));
+  __ add(Rtemp, Rtemp, (-Method::itable_index_max)); // small negative constant is too large for an immediate on arm32
+  __ neg(Rindex, Rtemp);
+
+  __ lookup_interface_method(// inputs: rec. class, interface
+                             Rklass, Rinterf, Rindex,
+                             // outputs:  scan temp. reg1, scan temp. reg2
+                             Rmethod, Ritable, Rtemp,
+                             no_such_interface);
 
   // Rmethod: Method* to call
 
@@ -4278,6 +4261,13 @@
 
   // do the call
   __ jump_from_interpreted(Rmethod);
+
+  // throw exception
+  __ bind(no_such_interface);
+  __ restore_method();
+  __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_IncompatibleClassChangeError));
+  // the call_VM checks for exception, so we should never return here.
+  __ should_not_reach_here();
 }
 
 void TemplateTable::invokehandle(int byte_no) {
@@ -4345,7 +4335,6 @@
   Label done;
   Label initialize_header;
   Label initialize_object;  // including clearing the fields
-  Label allocate_shared;
 
   const bool allow_shared_alloc =
     Universe::heap()->supports_inline_contig_alloc();
@@ -4390,13 +4379,19 @@
   // Klass::_lh_instance_slow_path_bit is really a bit mask, not bit number
   __ tbnz(Rsize, exact_log2(Klass::_lh_instance_slow_path_bit), slow_case);
 
+  // Allocate the instance:
+  //  If TLAB is enabled:
+  //    Try to allocate in the TLAB.
+  //    If fails, go to the slow path.
+  //  Else If inline contiguous allocations are enabled:
+  //    Try to allocate in eden.
+  //    If fails due to heap end, go to slow path.
   //
-  // Allocate the instance
-  // 1) Try to allocate in the TLAB
-  // 2) if fail and the object is large allocate in the shared Eden
-  // 3) if the above fails (or is not applicable), go to a slow case
-  // (creates a new TLAB, etc.)
-
+  //  If TLAB is enabled OR inline contiguous is enabled:
+  //    Initialize the allocation.
+  //    Exit.
+  //
+  //  Go to slow path.
   if (UseTLAB) {
     const Register Rtlab_top = R1_tmp;
     const Register Rtlab_end = R2_tmp;
@@ -4406,7 +4401,7 @@
     __ ldr(Rtlab_end, Address(Rthread, in_bytes(JavaThread::tlab_end_offset())));
     __ add(Rtlab_top, Robj, Rsize);
     __ cmp(Rtlab_top, Rtlab_end);
-    __ b(allow_shared_alloc ? allocate_shared : slow_case, hi);
+    __ b(slow_case, hi);
     __ str(Rtlab_top, Address(Rthread, JavaThread::tlab_top_offset()));
     if (ZeroTLAB) {
       // the fields have been already cleared
@@ -4415,45 +4410,43 @@
       // initialize both the header and fields
       __ b(initialize_object);
     }
-  }
-
-  // Allocation in the shared Eden, if allowed.
-  if (allow_shared_alloc) {
-    __ bind(allocate_shared);
-
-    const Register Rheap_top_addr = R2_tmp;
-    const Register Rheap_top = R5_tmp;
-    const Register Rheap_end = Rtemp;
-    assert_different_registers(Robj, Rklass, Rsize, Rheap_top_addr, Rheap_top, Rheap_end, LR);
-
-    // heap_end now (re)loaded in the loop since also used as a scratch register in the CAS
-    __ ldr_literal(Rheap_top_addr, Lheap_top_addr);
-
-    Label retry;
-    __ bind(retry);
+  } else {
+    // Allocation in the shared Eden, if allowed.
+    if (allow_shared_alloc) {
+      const Register Rheap_top_addr = R2_tmp;
+      const Register Rheap_top = R5_tmp;
+      const Register Rheap_end = Rtemp;
+      assert_different_registers(Robj, Rklass, Rsize, Rheap_top_addr, Rheap_top, Rheap_end, LR);
+
+      // heap_end now (re)loaded in the loop since also used as a scratch register in the CAS
+      __ ldr_literal(Rheap_top_addr, Lheap_top_addr);
+
+      Label retry;
+      __ bind(retry);
 
 #ifdef AARCH64
-    __ ldxr(Robj, Rheap_top_addr);
+      __ ldxr(Robj, Rheap_top_addr);
 #else
-    __ ldr(Robj, Address(Rheap_top_addr));
+      __ ldr(Robj, Address(Rheap_top_addr));
 #endif // AARCH64
 
-    __ ldr(Rheap_end, Address(Rheap_top_addr, (intptr_t)Universe::heap()->end_addr()-(intptr_t)Universe::heap()->top_addr()));
-    __ add(Rheap_top, Robj, Rsize);
-    __ cmp(Rheap_top, Rheap_end);
-    __ b(slow_case, hi);
-
-    // Update heap top atomically.
-    // If someone beats us on the allocation, try again, otherwise continue.
+      __ ldr(Rheap_end, Address(Rheap_top_addr, (intptr_t)Universe::heap()->end_addr()-(intptr_t)Universe::heap()->top_addr()));
+      __ add(Rheap_top, Robj, Rsize);
+      __ cmp(Rheap_top, Rheap_end);
+      __ b(slow_case, hi);
+
+      // Update heap top atomically.
+      // If someone beats us on the allocation, try again, otherwise continue.
 #ifdef AARCH64
-    __ stxr(Rtemp2, Rheap_top, Rheap_top_addr);
-    __ cbnz_w(Rtemp2, retry);
+      __ stxr(Rtemp2, Rheap_top, Rheap_top_addr);
+      __ cbnz_w(Rtemp2, retry);
 #else
-    __ atomic_cas_bool(Robj, Rheap_top, Rheap_top_addr, 0, Rheap_end/*scratched*/);
-    __ b(retry, ne);
+      __ atomic_cas_bool(Robj, Rheap_top, Rheap_top_addr, 0, Rheap_end/*scratched*/);
+      __ b(retry, ne);
 #endif // AARCH64
 
-    __ incr_allocated_bytes(Rsize, Rtemp);
+      __ incr_allocated_bytes(Rsize, Rtemp);
+    }
   }
 
   if (UseTLAB || allow_shared_alloc) {
--- a/src/hotspot/cpu/arm/vtableStubs_arm.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/cpu/arm/vtableStubs_arm.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -28,6 +28,7 @@
 #include "code/vtableStubs.hpp"
 #include "interp_masm_arm.hpp"
 #include "memory/resourceArea.hpp"
+#include "oops/compiledICHolder.hpp"
 #include "oops/instanceKlass.hpp"
 #include "oops/klassVtable.hpp"
 #include "runtime/sharedRuntime.hpp"
@@ -118,67 +119,48 @@
 
   // R0-R3 / R0-R7 registers hold the arguments and cannot be spoiled
   const Register Rclass  = AARCH64_ONLY(R9)  NOT_AARCH64(R4);
-  const Register Rlength = AARCH64_ONLY(R10)  NOT_AARCH64(R5);
+  const Register Rintf   = AARCH64_ONLY(R10) NOT_AARCH64(R5);
   const Register Rscan   = AARCH64_ONLY(R11) NOT_AARCH64(R6);
-  const Register tmp     = Rtemp;
 
-  assert_different_registers(Ricklass, Rclass, Rlength, Rscan, tmp);
+  assert_different_registers(Ricklass, Rclass, Rintf, Rscan, Rtemp);
 
   // Calculate the start of itable (itable goes after vtable)
   const int scale = exact_log2(vtableEntry::size_in_bytes());
   address npe_addr = __ pc();
   __ load_klass(Rclass, R0);
-  __ ldr_s32(Rlength, Address(Rclass, Klass::vtable_length_offset()));
 
-  __ add(Rscan, Rclass, in_bytes(Klass::vtable_start_offset()));
-  __ add(Rscan, Rscan, AsmOperand(Rlength, lsl, scale));
-
-  // Search through the itable for an interface equal to incoming Ricklass
-  // itable looks like [intface][offset][intface][offset][intface][offset]
-  const int entry_size = itableOffsetEntry::size() * HeapWordSize;
-  assert(itableOffsetEntry::interface_offset_in_bytes() == 0, "not added for convenience");
+  Label L_no_such_interface;
 
-  Label loop;
-  __ bind(loop);
-  __ ldr(tmp, Address(Rscan, entry_size, post_indexed));
-#ifdef AARCH64
-  Label found;
-  __ cmp(tmp, Ricklass);
-  __ b(found, eq);
-  __ cbnz(tmp, loop);
-#else
-  __ cmp(tmp, Ricklass);  // set ZF and CF if interface is found
-  __ cmn(tmp, 0, ne);     // check if tmp == 0 and clear CF if it is
-  __ b(loop, ne);
-#endif // AARCH64
+  // Receiver subtype check against REFC.
+  __ ldr(Rintf, Address(Ricklass, CompiledICHolder::holder_klass_offset()));
+  __ lookup_interface_method(// inputs: rec. class, interface, itable index
+                             Rclass, Rintf, noreg,
+                             // outputs: temp reg1, temp reg2
+                             noreg, Rscan, Rtemp,
+                             L_no_such_interface);
 
-  assert(StubRoutines::throw_IncompatibleClassChangeError_entry() != NULL, "Check initialization order");
-#ifdef AARCH64
-  __ jump(StubRoutines::throw_IncompatibleClassChangeError_entry(), relocInfo::runtime_call_type, tmp);
-  __ bind(found);
-#else
-  // CF == 0 means we reached the end of itable without finding icklass
-  __ jump(StubRoutines::throw_IncompatibleClassChangeError_entry(), relocInfo::runtime_call_type, noreg, cc);
-#endif // !AARCH64
-
-  // Interface found at previous position of Rscan, now load the method oop
-  __ ldr_s32(tmp, Address(Rscan, itableOffsetEntry::offset_offset_in_bytes() - entry_size));
-  {
-    const int method_offset = itableMethodEntry::size() * HeapWordSize * itable_index +
-      itableMethodEntry::method_offset_in_bytes();
-    __ add_slow(Rmethod, Rclass, method_offset);
-  }
-  __ ldr(Rmethod, Address(Rmethod, tmp));
+  // Get Method* and entry point for compiler
+  __ ldr(Rintf, Address(Ricklass, CompiledICHolder::holder_metadata_offset()));
+  __ lookup_interface_method(// inputs: rec. class, interface, itable index
+                             Rclass, Rintf, itable_index,
+                             // outputs: temp reg1, temp reg2, temp reg3
+                             Rmethod, Rscan, Rtemp,
+                             L_no_such_interface);
 
   address ame_addr = __ pc();
 
 #ifdef AARCH64
-  __ ldr(tmp, Address(Rmethod, Method::from_compiled_offset()));
-  __ br(tmp);
+  __ ldr(Rtemp, Address(Rmethod, Method::from_compiled_offset()));
+  __ br(Rtemp);
 #else
   __ ldr(PC, Address(Rmethod, Method::from_compiled_offset()));
 #endif // AARCH64
 
+  __ bind(L_no_such_interface);
+
+  assert(StubRoutines::throw_IncompatibleClassChangeError_entry() != NULL, "check initialization order");
+  __ jump(StubRoutines::throw_IncompatibleClassChangeError_entry(), relocInfo::runtime_call_type, Rtemp);
+
   masm->flush();
 
   if (PrintMiscellaneous && (WizardMode || Verbose)) {
@@ -205,7 +187,7 @@
     instr_count = NOT_AARCH64(4) AARCH64_ONLY(5);
   } else {
     // itable stub size
-    instr_count = NOT_AARCH64(20) AARCH64_ONLY(20);
+    instr_count = NOT_AARCH64(31) AARCH64_ONLY(31);
   }
 
 #ifdef AARCH64
--- a/src/hotspot/cpu/ppc/c1_MacroAssembler_ppc.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/cpu/ppc/c1_MacroAssembler_ppc.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,6 +1,6 @@
 /*
- * Copyright (c) 1999, 2015, Oracle and/or its affiliates. All rights reserved.
- * Copyright (c) 2012, 2015 SAP SE. All rights reserved.
+ * Copyright (c) 1999, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2018 SAP SE. 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,8 +34,8 @@
 #include "runtime/basicLock.hpp"
 #include "runtime/biasedLocking.hpp"
 #include "runtime/os.hpp"
+#include "runtime/sharedRuntime.hpp"
 #include "runtime/stubRoutines.hpp"
-#include "runtime/sharedRuntime.hpp"
 #include "utilities/align.hpp"
 
 
--- a/src/hotspot/cpu/ppc/c1_globals_ppc.hpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/cpu/ppc/c1_globals_ppc.hpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,6 +1,6 @@
 /*
- * Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.
- * Copyright (c) 2012, 2015 SAP SE. All rights reserved.
+ * Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2018 SAP SE. 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,36 +33,36 @@
 // (see c1_globals.hpp)
 
 #ifndef TIERED
-define_pd_global(bool, BackgroundCompilation,        true );
-define_pd_global(bool, CICompileOSR,                 true );
-define_pd_global(bool, InlineIntrinsics,             true );
-define_pd_global(bool, PreferInterpreterNativeStubs, false);
-define_pd_global(bool, ProfileTraps,                 false);
-define_pd_global(bool, UseOnStackReplacement,        true );
-define_pd_global(bool, TieredCompilation,            false);
-define_pd_global(intx, CompileThreshold,             1000 );
+define_pd_global(bool,     BackgroundCompilation,        true);
+define_pd_global(bool,     CICompileOSR,                 true);
+define_pd_global(bool,     InlineIntrinsics,             true);
+define_pd_global(bool,     PreferInterpreterNativeStubs, false);
+define_pd_global(bool,     ProfileTraps,                 false);
+define_pd_global(bool,     UseOnStackReplacement,        true);
+define_pd_global(bool,     TieredCompilation,            false);
+define_pd_global(intx,     CompileThreshold,             1000);
 
-define_pd_global(intx, OnStackReplacePercentage,     1400 );
-define_pd_global(bool, UseTLAB,                      true );
-define_pd_global(bool, ProfileInterpreter,           false);
-define_pd_global(intx, FreqInlineSize,               325  );
-define_pd_global(bool, ResizeTLAB,                   true );
-define_pd_global(intx, ReservedCodeCacheSize,        32*M );
-define_pd_global(intx, CodeCacheExpansionSize,       32*K );
-define_pd_global(uintx,CodeCacheMinBlockLength,      1);
-define_pd_global(uintx,MetaspaceSize,                12*M );
-define_pd_global(bool, NeverActAsServerClassMachine, true );
-define_pd_global(intx, NewSizeThreadIncrease,        16*K );
-define_pd_global(uint64_t,MaxRAM,                    1ULL*G);
-define_pd_global(intx, InitialCodeCacheSize,         160*K);
+define_pd_global(intx,     OnStackReplacePercentage,     1400);
+define_pd_global(bool,     UseTLAB,                      true);
+define_pd_global(bool,     ProfileInterpreter,           false);
+define_pd_global(intx,     FreqInlineSize,               325 );
+define_pd_global(bool,     ResizeTLAB,                   true);
+define_pd_global(uintx,    ReservedCodeCacheSize,        32*M);
+define_pd_global(uintx,    CodeCacheExpansionSize,       32*K);
+define_pd_global(uintx,    CodeCacheMinBlockLength,      1);
+define_pd_global(size_t,   MetaspaceSize,                12*M);
+define_pd_global(bool,     NeverActAsServerClassMachine, true);
+define_pd_global(size_t,   NewSizeThreadIncrease,        16*K);
+define_pd_global(uint64_t, MaxRAM,                       1ULL*G);
+define_pd_global(uintx,    InitialCodeCacheSize,         160*K);
 #endif // !TIERED
 
-define_pd_global(bool, UseTypeProfile,               false);
-define_pd_global(bool, RoundFPResults,               false);
+define_pd_global(bool,     UseTypeProfile,               false);
+define_pd_global(bool,     RoundFPResults,               false);
 
-define_pd_global(bool, LIRFillDelaySlots,            false);
-define_pd_global(bool, OptimizeSinglePrecision,      false);
-define_pd_global(bool, CSEArrayLength,               true );
-define_pd_global(bool, TwoOperandLIRForm,            false);
+define_pd_global(bool,     LIRFillDelaySlots,            false);
+define_pd_global(bool,     OptimizeSinglePrecision,      false);
+define_pd_global(bool,     CSEArrayLength,               true);
+define_pd_global(bool,     TwoOperandLIRForm,            false);
 
 #endif // CPU_PPC_VM_C1_GLOBALS_PPC_HPP
--- a/src/hotspot/cpu/ppc/c2_globals_ppc.hpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/cpu/ppc/c2_globals_ppc.hpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,6 +1,6 @@
 /*
- * Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.
- * Copyright (c) 2012, 2016 SAP SE. All rights reserved.
+ * Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2018 SAP SE. 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
@@ -39,7 +39,7 @@
 define_pd_global(bool, ProfileTraps,                 true);
 define_pd_global(bool, UseOnStackReplacement,        true);
 define_pd_global(bool, ProfileInterpreter,           true);
-define_pd_global(bool, TieredCompilation,            true);
+define_pd_global(bool, TieredCompilation,            trueInTiered);
 define_pd_global(intx, CompileThreshold,             10000);
 
 define_pd_global(intx, OnStackReplacePercentage,     140);
@@ -78,27 +78,27 @@
 //   x.f = 0
 //   loc = x.f
 //   NullCheck loc
-define_pd_global(bool, OptoScheduling,               false);
-define_pd_global(bool, IdealizeClearArrayNode,       true);
+define_pd_global(bool,     OptoScheduling,               false);
+define_pd_global(bool,     IdealizeClearArrayNode,       true);
 
-define_pd_global(intx, InitialCodeCacheSize,         2048*K); // Integral multiple of CodeCacheExpansionSize
-define_pd_global(intx, ReservedCodeCacheSize,        256*M);
-define_pd_global(intx, NonProfiledCodeHeapSize,      125*M);
-define_pd_global(intx, ProfiledCodeHeapSize,         126*M);
-define_pd_global(intx, NonNMethodCodeHeapSize,       5*M  );
-define_pd_global(intx, CodeCacheExpansionSize,       64*K);
+define_pd_global(uintx,    InitialCodeCacheSize,         2048*K); // Integral multiple of CodeCacheExpansionSize
+define_pd_global(uintx,    ReservedCodeCacheSize,        256*M);
+define_pd_global(uintx,    NonProfiledCodeHeapSize,      125*M);
+define_pd_global(uintx,    ProfiledCodeHeapSize,         126*M);
+define_pd_global(uintx,    NonNMethodCodeHeapSize,       5*M  );
+define_pd_global(uintx,    CodeCacheExpansionSize,       64*K);
 
 // Ergonomics related flags
-define_pd_global(uint64_t, MaxRAM,                   4ULL*G);
-define_pd_global(uintx, CodeCacheMinBlockLength,     4);
-define_pd_global(uintx, CodeCacheMinimumUseSpace,    400*K);
+define_pd_global(uint64_t, MaxRAM,                       128ULL*G);
+define_pd_global(uintx,    CodeCacheMinBlockLength,      4);
+define_pd_global(uintx,    CodeCacheMinimumUseSpace,     400*K);
 
-define_pd_global(bool,  TrapBasedRangeChecks,        true);
+define_pd_global(bool,     TrapBasedRangeChecks,          true);
 
 // Heap related flags
-define_pd_global(size_t, MetaspaceSize,              ScaleForWordSize(16*M));
+define_pd_global(size_t,   MetaspaceSize,                ScaleForWordSize(16*M));
 
 // Ergonomics related flags
-define_pd_global(bool, NeverActAsServerClassMachine, false);
+define_pd_global(bool,     NeverActAsServerClassMachine, false);
 
 #endif // CPU_PPC_VM_C2_GLOBALS_PPC_HPP
--- a/src/hotspot/cpu/ppc/c2_init_ppc.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/cpu/ppc/c2_init_ppc.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,6 +1,6 @@
 /*
- * Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.
- * Copyright (c) 2012, 2015 SAP SE. All rights reserved.
+ * Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2018 SAP SE. 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
@@ -29,11 +29,11 @@
 #include "runtime/globals.hpp"
 #include "utilities/debug.hpp"
 
-// processor dependent initialization for ppc
+// Processor dependent initialization of C2 compiler for ppc.
 
 void Compile::pd_compiler2_init() {
 
-  // Power7 and later
+  // Power7 and later.
   if (PowerArchitecturePPC64 > 6) {
     if (FLAG_IS_DEFAULT(UsePopCountInstruction)) {
       FLAG_SET_ERGO(bool, UsePopCountInstruction, true);
--- a/src/hotspot/cpu/ppc/globals_ppc.hpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/cpu/ppc/globals_ppc.hpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,6 +1,6 @@
 /*
- * Copyright (c) 2002, 2017, Oracle and/or its affiliates. All rights reserved.
- * Copyright (c) 2012, 2017 SAP SE. All rights reserved.
+ * Copyright (c) 2002, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2018 SAP SE. 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
@@ -86,14 +86,14 @@
 define_pd_global(bool, ThreadLocalHandshakes, true);
 
 // Platform dependent flag handling: flags only defined on this platform.
-#define ARCH_FLAGS(develop, \
-                   product, \
-                   diagnostic, \
+#define ARCH_FLAGS(develop,      \
+                   product,      \
+                   diagnostic,   \
                    experimental, \
-                   notproduct, \
-                   range, \
-                   constraint, \
-                   writeable)  \
+                   notproduct,   \
+                   range,        \
+                   constraint,   \
+                   writeable)    \
                                                                             \
   product(uintx, PowerArchitecturePPC64, 0,                                 \
           "CPU Version: x for PowerX. Currently recognizes Power5 to "      \
--- a/src/hotspot/cpu/ppc/icache_ppc.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/cpu/ppc/icache_ppc.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,6 +1,6 @@
 /*
- * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
- * Copyright (c) 2012, 2013 SAP SE. All rights reserved.
+ * Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2018 SAP SE. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -24,7 +24,6 @@
  */
 
 #include "precompiled.hpp"
-#include "assembler_ppc.inline.hpp"
 #include "runtime/icache.hpp"
 
 // Use inline assembler to implement icache flush.
@@ -32,7 +31,7 @@
   address end = start + (unsigned int)lines*ICache::line_size;
   assert(start <= end, "flush_icache parms");
 
-  // store modified cache lines from data cache
+  // Store modified cache lines from data cache.
   for (address a = start; a < end; a += ICache::line_size) {
     __asm__ __volatile__(
      "dcbst 0, %0  \n"
@@ -48,7 +47,7 @@
      :
      : "memory");
 
-  // invalidate respective cache lines in instruction cache
+  // Invalidate respective cache lines in instruction cache.
   for (address a = start; a < end; a += ICache::line_size) {
     __asm__ __volatile__(
      "icbi 0, %0   \n"
@@ -57,7 +56,7 @@
      : "memory");
   }
 
-  // discard fetched instructions
+  // Discard fetched instructions.
   __asm__ __volatile__(
      "isync \n"
      :
@@ -71,6 +70,8 @@
 
   *flush_icache_stub = (ICache::flush_icache_stub_t)ICache::ppc64_flush_icache;
 
-  // First call to flush itself
+  // First call to flush itself.
+  // Pointless since we call C, but it is expected to get
+  // executed during VM_Version::determine_features().
   ICache::invalidate_range((address)(*flush_icache_stub), 0);
 }
--- a/src/hotspot/cpu/ppc/interp_masm_ppc_64.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/cpu/ppc/interp_masm_ppc_64.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,6 +1,6 @@
 /*
- * Copyright (c) 2003, 2017, Oracle and/or its affiliates. All rights reserved.
- * Copyright (c) 2012, 2017 SAP SE. All rights reserved.
+ * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2018 SAP SE. 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
@@ -32,6 +32,10 @@
 #include "runtime/safepointMechanism.hpp"
 #include "runtime/sharedRuntime.hpp"
 
+// Implementation of InterpreterMacroAssembler.
+
+// This file specializes the assembler with interpreter-specific macros.
+
 #ifdef PRODUCT
 #define BLOCK_COMMENT(str) // nothing
 #else
--- a/src/hotspot/cpu/ppc/jniFastGetField_ppc.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/cpu/ppc/jniFastGetField_ppc.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,6 +1,6 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
- * Copyright (c) 2012, 2013 SAP SE. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2018 SAP SE. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -24,7 +24,7 @@
  */
 
 #include "precompiled.hpp"
-#include "assembler_ppc.inline.hpp"
+#include "asm/assembler.inline.hpp"
 #include "memory/resourceArea.hpp"
 #include "prims/jniFastGetField.hpp"
 #include "prims/jvm_misc.hpp"
--- a/src/hotspot/cpu/ppc/macroAssembler_ppc.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/cpu/ppc/macroAssembler_ppc.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * Copyright (c) 2012, 2017, SAP SE. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
@@ -1788,11 +1788,10 @@
                                              RegisterOrConstant itable_index,
                                              Register method_result,
                                              Register scan_temp,
-                                             Register sethi_temp,
-                                             Label& L_no_such_interface) {
+                                             Register temp2,
+                                             Label& L_no_such_interface,
+                                             bool return_method) {
   assert_different_registers(recv_klass, intf_klass, method_result, scan_temp);
-  assert(itable_index.is_constant() || itable_index.as_register() == method_result,
-         "caller must use same register for non-constant itable index as for method");
 
   // Compute start of first itableOffsetEntry (which is at the end of the vtable).
   int vtable_base = in_bytes(Klass::vtable_start_offset());
@@ -1810,15 +1809,17 @@
   add(scan_temp, recv_klass, scan_temp);
 
   // Adjust recv_klass by scaled itable_index, so we can free itable_index.
-  if (itable_index.is_register()) {
-    Register itable_offset = itable_index.as_register();
-    sldi(itable_offset, itable_offset, logMEsize);
-    if (itentry_off) addi(itable_offset, itable_offset, itentry_off);
-    add(recv_klass, itable_offset, recv_klass);
-  } else {
-    long itable_offset = (long)itable_index.as_constant();
-    load_const_optimized(sethi_temp, (itable_offset<<logMEsize)+itentry_off); // static address, no relocation
-    add(recv_klass, sethi_temp, recv_klass);
+  if (return_method) {
+    if (itable_index.is_register()) {
+      Register itable_offset = itable_index.as_register();
+      sldi(method_result, itable_offset, logMEsize);
+      if (itentry_off) { addi(method_result, method_result, itentry_off); }
+      add(method_result, method_result, recv_klass);
+    } else {
+      long itable_offset = (long)itable_index.as_constant();
+      // static address, no relocation
+      add_const_optimized(method_result, recv_klass, (itable_offset << logMEsize) + itentry_off, temp2);
+    }
   }
 
   // for (scan = klass->itable(); scan->interface() != NULL; scan += scan_step) {
@@ -1831,12 +1832,12 @@
   for (int peel = 1; peel >= 0; peel--) {
     // %%%% Could load both offset and interface in one ldx, if they were
     // in the opposite order. This would save a load.
-    ld(method_result, itableOffsetEntry::interface_offset_in_bytes(), scan_temp);
+    ld(temp2, itableOffsetEntry::interface_offset_in_bytes(), scan_temp);
 
     // Check that this entry is non-null. A null entry means that
     // the receiver class doesn't implement the interface, and wasn't the
     // same as when the caller was compiled.
-    cmpd(CCR0, method_result, intf_klass);
+    cmpd(CCR0, temp2, intf_klass);
 
     if (peel) {
       beq(CCR0, found_method);
@@ -1849,7 +1850,7 @@
 
     bind(search);
 
-    cmpdi(CCR0, method_result, 0);
+    cmpdi(CCR0, temp2, 0);
     beq(CCR0, L_no_such_interface);
     addi(scan_temp, scan_temp, scan_step);
   }
@@ -1857,9 +1858,11 @@
   bind(found_method);
 
   // Got a hit.
-  int ito_offset = itableOffsetEntry::offset_offset_in_bytes();
-  lwz(scan_temp, ito_offset, scan_temp);
-  ldx(method_result, scan_temp, recv_klass);
+  if (return_method) {
+    int ito_offset = itableOffsetEntry::offset_offset_in_bytes();
+    lwz(scan_temp, ito_offset, scan_temp);
+    ldx(method_result, scan_temp, method_result);
+  }
 }
 
 // virtual method calling
@@ -2880,10 +2883,6 @@
     //assert(ObjectMonitor::recursions_size_in_bytes() == 8, "unexpected size");
     asm_assert_mem8_is_zero(ObjectMonitor::recursions_offset_in_bytes(), temp,
                             "monitor->_recursions should be 0", -1);
-    // Invariant 2: OwnerIsThread shouldn't be 0.
-    //assert(ObjectMonitor::OwnerIsThread_size_in_bytes() == 4, "unexpected size");
-    //asm_assert_mem4_isnot_zero(ObjectMonitor::OwnerIsThread_offset_in_bytes(), temp,
-    //                           "monitor->OwnerIsThread shouldn't be 0", -1);
 #   endif
 
 #if INCLUDE_RTM_OPT
--- a/src/hotspot/cpu/ppc/macroAssembler_ppc.hpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/cpu/ppc/macroAssembler_ppc.hpp	Fri Jan 19 09:32:10 2018 -0800
@@ -519,7 +519,8 @@
                                RegisterOrConstant itable_index,
                                Register method_result,
                                Register temp_reg, Register temp2_reg,
-                               Label& no_such_interface);
+                               Label& no_such_interface,
+                               bool return_method = true);
 
   // virtual method calling
   void lookup_virtual_method(Register recv_klass,
--- a/src/hotspot/cpu/ppc/nativeInst_ppc.hpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/cpu/ppc/nativeInst_ppc.hpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,6 +1,6 @@
 /*
- * Copyright (c) 2002, 2015, Oracle and/or its affiliates. All rights reserved.
- * Copyright (c) 2012, 2015 SAP SE. All rights reserved.
+ * Copyright (c) 2002, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2018 SAP SE. 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
@@ -26,7 +26,6 @@
 #ifndef CPU_PPC_VM_NATIVEINST_PPC_HPP
 #define CPU_PPC_VM_NATIVEINST_PPC_HPP
 
-#include "asm/assembler.hpp"
 #include "asm/macroAssembler.hpp"
 #include "memory/allocation.hpp"
 #include "runtime/icache.hpp"
--- a/src/hotspot/cpu/ppc/runtime_ppc.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/cpu/ppc/runtime_ppc.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,6 +1,6 @@
 /*
- * Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved.
- * Copyright (c) 2012, 2015 SAP SE. All rights reserved.
+ * Copyright (c) 1998, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2018 SAP SE. 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
@@ -25,7 +25,6 @@
 
 #include "precompiled.hpp"
 #ifdef COMPILER2
-#include "asm/assembler.inline.hpp"
 #include "asm/macroAssembler.inline.hpp"
 #include "classfile/systemDictionary.hpp"
 #include "code/vmreg.hpp"
--- a/src/hotspot/cpu/ppc/sharedRuntime_ppc.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/cpu/ppc/sharedRuntime_ppc.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,6 +1,6 @@
 /*
- * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
- * Copyright (c) 2012, 2017 SAP SE. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2018 SAP SE. 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
@@ -1188,7 +1188,7 @@
   // Argument is valid and klass is as expected, continue.
 
   // Extract method from inline cache, verified entry point needs it.
-  __ ld(R19_method, CompiledICHolder::holder_method_offset(), ic);
+  __ ld(R19_method, CompiledICHolder::holder_metadata_offset(), ic);
   assert(R19_method == ic, "the inline cache register is dead here");
 
   __ ld(code, method_(code));
@@ -1912,8 +1912,8 @@
   // - *_slot_offset Indicates offset from SP in number of stack slots.
   // - *_offset      Indicates offset from SP in bytes.
 
-  int stack_slots = c_calling_convention(out_sig_bt, out_regs, out_regs2, total_c_args) // 1+2)
-                  + SharedRuntime::out_preserve_stack_slots(); // See c_calling_convention.
+  int stack_slots = c_calling_convention(out_sig_bt, out_regs, out_regs2, total_c_args) + // 1+2)
+                    SharedRuntime::out_preserve_stack_slots(); // See c_calling_convention.
 
   // Now the space for the inbound oop handle area.
   int total_save_slots = num_java_iarg_registers * VMRegImpl::slots_per_word;
@@ -2044,7 +2044,8 @@
   OopMap    *oop_map  = new OopMap(stack_slots * 2, 0 /* arg_slots*/);
 
   if (is_critical_native) {
-    check_needs_gc_for_critical_native(masm, stack_slots, total_in_args, oop_handle_slot_offset, oop_maps, in_regs, in_sig_bt, r_temp_1);
+    check_needs_gc_for_critical_native(masm, stack_slots, total_in_args, oop_handle_slot_offset,
+                                       oop_maps, in_regs, in_sig_bt, r_temp_1);
   }
 
   // Move arguments from register/stack to register/stack.
--- a/src/hotspot/cpu/ppc/stubGenerator_ppc.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/cpu/ppc/stubGenerator_ppc.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * Copyright (c) 2012, 2017, SAP SE. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
@@ -40,6 +40,10 @@
 #include "runtime/thread.inline.hpp"
 #include "utilities/align.hpp"
 
+// Declaration and definition of StubGenerator (no .hpp file).
+// For a more detailed description of the stub routine structure
+// see the comment in stubRoutines.hpp.
+
 #define __ _masm->
 
 #ifdef PRODUCT
--- a/src/hotspot/cpu/ppc/stubRoutines_ppc_64.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/cpu/ppc/stubRoutines_ppc_64.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2018, Oracle and/or its affiliates. All rights reserved.
  * Copyright (c) 2012, 2017, SAP SE. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
@@ -23,6 +23,7 @@
  *
  */
 
+#include "precompiled.hpp"
 #include "asm/macroAssembler.inline.hpp"
 #include "runtime/stubRoutines.hpp"
 
--- a/src/hotspot/cpu/ppc/templateInterpreterGenerator_ppc.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/cpu/ppc/templateInterpreterGenerator_ppc.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 2018, Oracle and/or its affiliates. All rights reserved.
  * Copyright (c) 2015, 2017, SAP SE. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
@@ -582,25 +582,6 @@
   return entry;
 }
 
-#if 0
-// Call special ClassCastException constructor taking object to cast
-// and target class as arguments.
-address TemplateInterpreterGenerator::generate_ClassCastException_verbose_handler() {
-  address entry = __ pc();
-
-  // Expression stack must be empty before entering the VM if an
-  // exception happened.
-  __ empty_expression_stack();
-
-  // Thread will be loaded to R3_ARG1.
-  // Target class oop is in register R5_ARG3 by convention!
-  __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_ClassCastException_verbose), R17_tos, R5_ARG3);
-  // Above call must not return here since exception pending.
-  DEBUG_ONLY(__ should_not_reach_here();)
-  return entry;
-}
-#endif
-
 address TemplateInterpreterGenerator::generate_ClassCastException_handler() {
   address entry = __ pc();
   // Expression stack must be empty before entering the VM if an
@@ -1896,7 +1877,6 @@
   return NULL;
 }
 
-
 /**
  * Method entry for static native methods:
  *   int java.util.zip.CRC32.updateBytes(     int crc, byte[] b,  int off, int len)
--- a/src/hotspot/cpu/ppc/templateTable_ppc_64.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/cpu/ppc/templateTable_ppc_64.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -3486,11 +3486,11 @@
 void TemplateTable::invokeinterface_object_method(Register Rrecv_klass,
                                                   Register Rret,
                                                   Register Rflags,
-                                                  Register Rindex,
+                                                  Register Rmethod,
                                                   Register Rtemp1,
                                                   Register Rtemp2) {
 
-  assert_different_registers(Rindex, Rret, Rrecv_klass, Rflags, Rtemp1, Rtemp2);
+  assert_different_registers(Rmethod, Rret, Rrecv_klass, Rflags, Rtemp1, Rtemp2);
   Label LnotFinal;
 
   // Check for vfinal.
@@ -3502,14 +3502,14 @@
   // Final call case.
   __ profile_final_call(Rtemp1, Rscratch);
   // Argument and return type profiling.
-  __ profile_arguments_type(Rindex, Rscratch, Rrecv_klass /* scratch */, true);
+  __ profile_arguments_type(Rmethod, Rscratch, Rrecv_klass /* scratch */, true);
   // Do the final call - the index (f2) contains the method.
-  __ call_from_interpreter(Rindex, Rret, Rscratch, Rrecv_klass /* scratch */);
+  __ call_from_interpreter(Rmethod, Rret, Rscratch, Rrecv_klass /* scratch */);
 
   // Non-final callc case.
   __ bind(LnotFinal);
   __ profile_virtual_call(Rrecv_klass, Rtemp1, Rscratch, false);
-  generate_vtable_call(Rrecv_klass, Rindex, Rret, Rscratch);
+  generate_vtable_call(Rrecv_klass, Rmethod, Rret, Rscratch);
 }
 
 void TemplateTable::invokeinterface(int byte_no) {
@@ -3518,58 +3518,61 @@
 
   const Register Rscratch1        = R11_scratch1,
                  Rscratch2        = R12_scratch2,
-                 Rscratch3        = R9_ARG7,
-                 Rscratch4        = R10_ARG8,
-                 Rtable_addr      = Rscratch2,
+                 Rmethod          = R6_ARG4,
+                 Rmethod2         = R9_ARG7,
                  Rinterface_klass = R5_ARG3,
-                 Rret_type        = R8_ARG6,
-                 Rret_addr        = Rret_type,
-                 Rindex           = R6_ARG4,
-                 Rreceiver        = R4_ARG2,
-                 Rrecv_klass      = Rreceiver,
+                 Rret_addr        = R8_ARG6,
+                 Rindex           = R10_ARG8,
+                 Rreceiver        = R3_ARG1,
+                 Rrecv_klass      = R4_ARG2,
                  Rflags           = R7_ARG5;
 
-  prepare_invoke(byte_no, Rinterface_klass, Rret_addr, Rindex, Rreceiver, Rflags, Rscratch1);
+  prepare_invoke(byte_no, Rinterface_klass, Rret_addr, Rmethod, Rreceiver, Rflags, Rscratch1);
 
   // Get receiver klass.
-  __ null_check_throw(Rreceiver, oopDesc::klass_offset_in_bytes(), Rscratch3);
+  __ null_check_throw(Rreceiver, oopDesc::klass_offset_in_bytes(), Rscratch2);
   __ load_klass(Rrecv_klass, Rreceiver);
 
   // Check corner case object method.
-  Label LobjectMethod;
-
+  Label LobjectMethod, L_no_such_interface, Lthrow_ame;
   __ testbitdi(CCR0, R0, Rflags, ConstantPoolCacheEntry::is_forced_virtual_shift);
   __ btrue(CCR0, LobjectMethod);
 
-  // Fallthrough: The normal invokeinterface case.
+  __ lookup_interface_method(Rrecv_klass, Rinterface_klass, noreg, noreg, Rscratch1, Rscratch2,
+                             L_no_such_interface, /*return_method=*/false);
+
   __ profile_virtual_call(Rrecv_klass, Rscratch1, Rscratch2, false);
 
   // Find entry point to call.
-  Label Lthrow_icc, Lthrow_ame;
-  // Result will be returned in Rindex.
-  __ mr(Rscratch4, Rrecv_klass);
-  __ mr(Rscratch3, Rindex);
-  __ lookup_interface_method(Rrecv_klass, Rinterface_klass, Rindex, Rindex, Rscratch1, Rscratch2, Lthrow_icc);
-
-  __ cmpdi(CCR0, Rindex, 0);
+
+  // Get declaring interface class from method
+  __ ld(Rinterface_klass, in_bytes(Method::const_offset()), Rmethod);
+  __ ld(Rinterface_klass, in_bytes(ConstMethod::constants_offset()), Rinterface_klass);
+  __ ld(Rinterface_klass, ConstantPool::pool_holder_offset_in_bytes(), Rinterface_klass);
+
+  // Get itable index from method
+  __ lwa(Rindex, in_bytes(Method::itable_index_offset()), Rmethod);
+  __ subfic(Rindex, Rindex, Method::itable_index_max);
+
+  __ lookup_interface_method(Rrecv_klass, Rinterface_klass, Rindex, Rmethod2, Rscratch1, Rscratch2,
+                             L_no_such_interface);
+
+  __ cmpdi(CCR0, Rmethod2, 0);
   __ beq(CCR0, Lthrow_ame);
   // Found entry. Jump off!
   // Argument and return type profiling.
-  __ profile_arguments_type(Rindex, Rscratch1, Rscratch2, true);
-  __ call_from_interpreter(Rindex, Rret_addr, Rscratch1, Rscratch2);
+  __ profile_arguments_type(Rmethod2, Rscratch1, Rscratch2, true);
+  //__ profile_called_method(Rindex, Rscratch1);
+  __ call_from_interpreter(Rmethod2, Rret_addr, Rscratch1, Rscratch2);
 
   // Vtable entry was NULL => Throw abstract method error.
   __ bind(Lthrow_ame);
-  __ mr(Rrecv_klass, Rscratch4);
-  __ mr(Rindex, Rscratch3);
   call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_AbstractMethodError));
 
   // Interface was not found => Throw incompatible class change error.
-  __ bind(Lthrow_icc);
-  __ mr(Rrecv_klass, Rscratch4);
+  __ bind(L_no_such_interface);
   call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_IncompatibleClassChangeError));
-
-  __ should_not_reach_here();
+  DEBUG_ONLY( __ should_not_reach_here(); )
 
   // Special case of invokeinterface called for virtual method of
   // java.lang.Object. See ConstantPoolCacheEntry::set_method() for details:
@@ -3577,7 +3580,7 @@
   // to handle this corner case. This code isn't produced by javac, but could
   // be produced by another compliant java compiler.
   __ bind(LobjectMethod);
-  invokeinterface_object_method(Rrecv_klass, Rret_addr, Rflags, Rindex, Rscratch1, Rscratch2);
+  invokeinterface_object_method(Rrecv_klass, Rret_addr, Rflags, Rmethod, Rscratch1, Rscratch2);
 }
 
 void TemplateTable::invokedynamic(int byte_no) {
--- a/src/hotspot/cpu/ppc/vtableStubs_ppc_64.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/cpu/ppc/vtableStubs_ppc_64.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,6 +1,6 @@
 /*
- * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
- * Copyright (c) 2012, 2016 SAP SE. All rights reserved.
+ * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2017 SAP SE. 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,6 +28,7 @@
 #include "code/vtableStubs.hpp"
 #include "interp_masm_ppc.hpp"
 #include "memory/resourceArea.hpp"
+#include "oops/compiledICHolder.hpp"
 #include "oops/instanceKlass.hpp"
 #include "oops/klassVtable.hpp"
 #include "runtime/sharedRuntime.hpp"
@@ -55,17 +56,22 @@
   // PPC port: use fixed size.
   const int code_length = VtableStub::pd_code_size_limit(true);
   VtableStub* s = new (code_length) VtableStub(true, vtable_index);
+
+  // Can be NULL if there is no free space in the code cache.
+  if (s == NULL) {
+    return NULL;
+  }
+
   ResourceMark rm;
   CodeBuffer cb(s->entry_point(), code_length);
   MacroAssembler* masm = new MacroAssembler(&cb);
-  address start_pc;
 
 #ifndef PRODUCT
   if (CountCompiledCalls) {
-    __ load_const(R11_scratch1, SharedRuntime::nof_megamorphic_calls_addr());
-    __ lwz(R12_scratch2, 0, R11_scratch1);
+    int offs = __ load_const_optimized(R11_scratch1, SharedRuntime::nof_megamorphic_calls_addr(), R12_scratch2, true);
+    __ lwz(R12_scratch2, offs, R11_scratch1);
     __ addi(R12_scratch2, R12_scratch2, 1);
-    __ stw(R12_scratch2, 0, R11_scratch1);
+    __ stw(R12_scratch2, offs, R11_scratch1);
   }
 #endif
 
@@ -116,6 +122,7 @@
   __ ld(R12_scratch2, in_bytes(Method::from_compiled_offset()), R19_method);
   __ mtctr(R12_scratch2);
   __ bctr();
+
   masm->flush();
 
   guarantee(__ pc() <= s->code_end(), "overflowed buffer");
@@ -125,10 +132,16 @@
   return s;
 }
 
-VtableStub* VtableStubs::create_itable_stub(int vtable_index) {
+VtableStub* VtableStubs::create_itable_stub(int itable_index) {
   // PPC port: use fixed size.
   const int code_length = VtableStub::pd_code_size_limit(false);
-  VtableStub* s = new (code_length) VtableStub(false, vtable_index);
+  VtableStub* s = new (code_length) VtableStub(false, itable_index);
+
+  // Can be NULL if there is no free space in the code cache.
+  if (s == NULL) {
+    return NULL;
+  }
+
   ResourceMark rm;
   CodeBuffer cb(s->entry_point(), code_length);
   MacroAssembler* masm = new MacroAssembler(&cb);
@@ -136,10 +149,10 @@
 
 #ifndef PRODUCT
   if (CountCompiledCalls) {
-    __ load_const(R11_scratch1, SharedRuntime::nof_megamorphic_calls_addr());
-    __ lwz(R12_scratch2, 0, R11_scratch1);
+    int offs = __ load_const_optimized(R11_scratch1, SharedRuntime::nof_megamorphic_calls_addr(), R12_scratch2, true);
+    __ lwz(R12_scratch2, offs, R11_scratch1);
     __ addi(R12_scratch2, R12_scratch2, 1);
-    __ stw(R12_scratch2, 0, R11_scratch1);
+    __ stw(R12_scratch2, offs, R11_scratch1);
   }
 #endif
 
@@ -148,62 +161,28 @@
   // Entry arguments:
   //  R19_method: Interface
   //  R3_ARG1:    Receiver
-  //
 
-  const Register rcvr_klass = R11_scratch1;
-  const Register vtable_len = R12_scratch2;
-  const Register itable_entry_addr = R21_tmp1;
-  const Register itable_interface = R22_tmp2;
+  Label L_no_such_interface;
+  const Register rcvr_klass = R11_scratch1,
+                 interface  = R12_scratch2,
+                 tmp1       = R21_tmp1,
+                 tmp2       = R22_tmp2;
 
-  // Get receiver klass.
-
-  // We might implicit NULL fault here.
   address npe_addr = __ pc(); // npe = null pointer exception
   __ null_check(R3_ARG1, oopDesc::klass_offset_in_bytes(), /*implicit only*/NULL);
   __ load_klass(rcvr_klass, R3_ARG1);
 
-  BLOCK_COMMENT("Load start of itable entries into itable_entry.");
-  __ lwz(vtable_len, in_bytes(Klass::vtable_length_offset()), rcvr_klass);
-  __ slwi(vtable_len, vtable_len, exact_log2(vtableEntry::size_in_bytes()));
-  __ add(itable_entry_addr, vtable_len, rcvr_klass);
-
-  // Loop over all itable entries until desired interfaceOop(Rinterface) found.
-  BLOCK_COMMENT("Increment itable_entry_addr in loop.");
-  const int vtable_base_offset = in_bytes(Klass::vtable_start_offset());
-  __ addi(itable_entry_addr, itable_entry_addr, vtable_base_offset + itableOffsetEntry::interface_offset_in_bytes());
-
-  const int itable_offset_search_inc = itableOffsetEntry::size() * wordSize;
-  Label search;
-  __ bind(search);
-  __ ld(itable_interface, 0, itable_entry_addr);
+  // Receiver subtype check against REFC.
+  __ ld(interface, CompiledICHolder::holder_klass_offset(), R19_method);
+  __ lookup_interface_method(rcvr_klass, interface, noreg,
+                             R0, tmp1, tmp2,
+                             L_no_such_interface, /*return_method=*/ false);
 
-  // Handle IncompatibleClassChangeError in itable stubs.
-  // If the entry is NULL then we've reached the end of the table
-  // without finding the expected interface, so throw an exception.
-  BLOCK_COMMENT("Handle IncompatibleClassChangeError in itable stubs.");
-  Label throw_icce;
-  __ cmpdi(CCR1, itable_interface, 0);
-  __ cmpd(CCR0, itable_interface, R19_method);
-  __ addi(itable_entry_addr, itable_entry_addr, itable_offset_search_inc);
-  __ beq(CCR1, throw_icce);
-  __ bne(CCR0, search);
-
-  // Entry found and itable_entry_addr points to it, get offset of vtable for interface.
-
-  const Register vtable_offset = R12_scratch2;
-  const Register itable_method = R11_scratch1;
-
-  const int vtable_offset_offset = (itableOffsetEntry::offset_offset_in_bytes() -
-                                    itableOffsetEntry::interface_offset_in_bytes()) -
-                                   itable_offset_search_inc;
-  __ lwz(vtable_offset, vtable_offset_offset, itable_entry_addr);
-
-  // Compute itableMethodEntry and get method and entry point for compiler.
-  const int method_offset = (itableMethodEntry::size() * wordSize * vtable_index) +
-    itableMethodEntry::method_offset_in_bytes();
-
-  __ add(itable_method, rcvr_klass, vtable_offset);
-  __ ld(R19_method, method_offset, itable_method);
+  // Get Method* and entrypoint for compiler
+  __ ld(interface, CompiledICHolder::holder_metadata_offset(), R19_method);
+  __ lookup_interface_method(rcvr_klass, interface, itable_index,
+                             R19_method, tmp1, tmp2,
+                             L_no_such_interface, /*return_method=*/ true);
 
 #ifndef PRODUCT
   if (DebugVtables) {
@@ -219,7 +198,7 @@
   address ame_addr = __ pc(); // ame = abstract method error
 
   // Must do an explicit check if implicit checks are disabled.
-  __ null_check(R19_method, in_bytes(Method::from_compiled_offset()), &throw_icce);
+  __ null_check(R19_method, in_bytes(Method::from_compiled_offset()), &L_no_such_interface);
   __ ld(R12_scratch2, in_bytes(Method::from_compiled_offset()), R19_method);
   __ mtctr(R12_scratch2);
   __ bctr();
@@ -229,8 +208,8 @@
   // We force resolving of the call site by jumping to the "handle
   // wrong method" stub, and so let the interpreter runtime do all the
   // dirty work.
-  __ bind(throw_icce);
-  __ load_const(R11_scratch1, SharedRuntime::get_handle_wrong_method_stub());
+  __ bind(L_no_such_interface);
+  __ load_const_optimized(R11_scratch1, SharedRuntime::get_handle_wrong_method_stub(), R12_scratch2);
   __ mtctr(R11_scratch1);
   __ bctr();
 
@@ -245,14 +224,15 @@
 int VtableStub::pd_code_size_limit(bool is_vtable_stub) {
   if (DebugVtables || CountCompiledCalls || VerifyOops) {
     return 1000;
-  } else {
-    int decode_klass_size = MacroAssembler::instr_size_for_decode_klass_not_null();
-    if (is_vtable_stub) {
-      return 20 + decode_klass_size +  8 + 8;   // Plain + cOops + Traps + safety
-    } else {
-      return 96 + decode_klass_size + 12 + 8;   // Plain + cOops + Traps + safety
-    }
+  }
+  int size = is_vtable_stub ? 20 + 8 : 164 + 20; // Plain + safety
+  if (UseCompressedClassPointers) {
+    size += MacroAssembler::instr_size_for_decode_klass_not_null();
   }
+  if (!ImplicitNullChecks || !os::zero_page_read_protected()) {
+    size += is_vtable_stub ? 8 : 12;
+  }
+  return size;
 }
 
 int VtableStub::pd_code_alignment() {
--- a/src/hotspot/cpu/s390/bytes_s390.hpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/cpu/s390/bytes_s390.hpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,6 +1,6 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
- * Copyright (c) 2016 SAP SE. All rights reserved.
+ * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2018 SAP SE. 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
@@ -42,11 +42,6 @@
   //
   // In short, it makes no sense on z/Architecture to piecemeal get or put unaligned data.
 
-  // Only swap on little endian machines => suffix `_le'.
-  static inline u2   swap_u2_le(u2 x) { return x; }
-  static inline u4   swap_u4_le(u4 x) { return x; }
-  static inline u8   swap_u8_le(u8 x) { return x; }
-
   static inline u2   get_native_u2(address p) { return *(u2*)p; }
   static inline u4   get_native_u4(address p) { return *(u4*)p; }
   static inline u8   get_native_u8(address p) { return *(u8*)p; }
@@ -55,7 +50,8 @@
   static inline void put_native_u4(address p, u4 x) { *(u4*)p = x; }
   static inline void put_native_u8(address p, u8 x) { *(u8*)p = x; }
 
-#include "bytes_linux_s390.inline.hpp"
+  // The following header contains the implementations of swap_u2, swap_u4, and swap_u8.
+#include OS_CPU_HEADER_INLINE(bytes)
 
   // Efficient reading and writing of unaligned unsigned data in Java byte ordering (i.e. big-endian ordering)
   static inline u2   get_Java_u2(address p) { return get_native_u2(p); }
--- a/src/hotspot/cpu/s390/c1_globals_s390.hpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/cpu/s390/c1_globals_s390.hpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,6 +1,6 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
- * Copyright (c) 2016 SAP SE. All rights reserved.
+ * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2018 SAP SE. 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
@@ -48,7 +48,7 @@
 define_pd_global(bool,     ProfileInterpreter,           false);
 define_pd_global(intx,     FreqInlineSize,               325);
 define_pd_global(bool,     ResizeTLAB,                   true);
-define_pd_global(intx,     ReservedCodeCacheSize,        32*M);
+define_pd_global(uintx,    ReservedCodeCacheSize,        32*M);
 define_pd_global(uintx,    NonProfiledCodeHeapSize,      13*M);
 define_pd_global(uintx,    ProfiledCodeHeapSize,         14*M);
 define_pd_global(uintx,    NonNMethodCodeHeapSize,       5*M);
--- a/src/hotspot/cpu/s390/c2_globals_s390.hpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/cpu/s390/c2_globals_s390.hpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,6 +1,6 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
- * Copyright (c) 2016 SAP SE. All rights reserved.
+ * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2018 SAP SE. 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
@@ -58,7 +58,7 @@
 define_pd_global(intx, LoopPercentProfileLimit,      10);
 define_pd_global(intx, MinJumpTableSize,             18);
 
-// Peephole and CISC spilling both break the graph, and so makes the
+// Peephole and CISC spilling both break the graph, and so make the
 // scheduler sick.
 define_pd_global(bool, OptoPeephole,                 false);
 define_pd_global(bool, UseCISCSpill,                 true);
--- a/src/hotspot/cpu/s390/globals_s390.hpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/cpu/s390/globals_s390.hpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,6 +1,6 @@
 /*
  * Copyright (c) 2016, 2017 Oracle and/or its affiliates. All rights reserved.
- * Copyright (c) 2016, 2017 SAP SE. All rights reserved.
+ * Copyright (c) 2016, 2018 SAP SE. 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
@@ -87,7 +87,14 @@
 
 define_pd_global(bool, ThreadLocalHandshakes, true);
 
-#define ARCH_FLAGS(develop, product, diagnostic, experimental, notproduct, range, constraint, writeable) \
+#define ARCH_FLAGS(develop,      \
+                   product,      \
+                   diagnostic,   \
+                   experimental, \
+                   notproduct,   \
+                   range,        \
+                   constraint,   \
+                   writeable)    \
                                                                               \
   /* Reoptimize code-sequences of calls at runtime, e.g. replace an */        \
   /* indirect call by a direct call.                                */        \
--- a/src/hotspot/cpu/s390/macroAssembler_s390.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/cpu/s390/macroAssembler_s390.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -2806,8 +2806,8 @@
                                              RegisterOrConstant itable_index,
                                              Register           method_result,
                                              Register           temp1_reg,
-                                             Register           temp2_reg,
-                                             Label&             no_such_interface) {
+                                             Label&             no_such_interface,
+                                             bool               return_method) {
 
   const Register vtable_len = temp1_reg;    // Used to compute itable_entry_addr.
   const Register itable_entry_addr = Z_R1_scratch;
@@ -2842,38 +2842,36 @@
   z_brne(search);
 
   // Entry found and itable_entry_addr points to it, get offset of vtable for interface.
-
-  const int vtable_offset_offset = (itableOffsetEntry::offset_offset_in_bytes() -
-                                    itableOffsetEntry::interface_offset_in_bytes()) -
-                                   itable_offset_search_inc;
-
-  // Compute itableMethodEntry and get method and entry point
-  // we use addressing with index and displacement, since the formula
-  // for computing the entry's offset has a fixed and a dynamic part,
-  // the latter depending on the matched interface entry and on the case,
-  // that the itable index has been passed as a register, not a constant value.
-  int method_offset = itableMethodEntry::method_offset_in_bytes();
-                           // Fixed part (displacement), common operand.
-  Register itable_offset;  // Dynamic part (index register).
-
-  if (itable_index.is_register()) {
-     // Compute the method's offset in that register, for the formula, see the
-     // else-clause below.
-     itable_offset = itable_index.as_register();
-
-     z_sllg(itable_offset, itable_offset, exact_log2(itableMethodEntry::size() * wordSize));
-     z_agf(itable_offset, vtable_offset_offset, itable_entry_addr);
-  } else {
-    itable_offset = Z_R1_scratch;
-    // Displacement increases.
-    method_offset += itableMethodEntry::size() * wordSize * itable_index.as_constant();
-
-    // Load index from itable.
-    z_llgf(itable_offset, vtable_offset_offset, itable_entry_addr);
-  }
-
-  // Finally load the method's oop.
-  z_lg(method_result, method_offset, itable_offset, recv_klass);
+  if (return_method) {
+    const int vtable_offset_offset = (itableOffsetEntry::offset_offset_in_bytes() -
+                                      itableOffsetEntry::interface_offset_in_bytes()) -
+                                     itable_offset_search_inc;
+
+    // Compute itableMethodEntry and get method and entry point
+    // we use addressing with index and displacement, since the formula
+    // for computing the entry's offset has a fixed and a dynamic part,
+    // the latter depending on the matched interface entry and on the case,
+    // that the itable index has been passed as a register, not a constant value.
+    int method_offset = itableMethodEntry::method_offset_in_bytes();
+                             // Fixed part (displacement), common operand.
+    Register itable_offset = method_result;  // Dynamic part (index register).
+
+    if (itable_index.is_register()) {
+       // Compute the method's offset in that register, for the formula, see the
+       // else-clause below.
+       z_sllg(itable_offset, itable_index.as_register(), exact_log2(itableMethodEntry::size() * wordSize));
+       z_agf(itable_offset, vtable_offset_offset, itable_entry_addr);
+    } else {
+      // Displacement increases.
+      method_offset += itableMethodEntry::size() * wordSize * itable_index.as_constant();
+
+      // Load index from itable.
+      z_llgf(itable_offset, vtable_offset_offset, itable_entry_addr);
+    }
+
+    // Finally load the method's oop.
+    z_lg(method_result, method_offset, itable_offset, recv_klass);
+  }
   BLOCK_COMMENT("} lookup_interface_method");
 }
 
--- a/src/hotspot/cpu/s390/macroAssembler_s390.hpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/cpu/s390/macroAssembler_s390.hpp	Fri Jan 19 09:32:10 2018 -0800
@@ -671,8 +671,8 @@
                                RegisterOrConstant itable_index,
                                Register           method_result,
                                Register           temp1_reg,
-                               Register           temp2_reg,
-                               Label&             no_such_interface);
+                               Label&             no_such_interface,
+                               bool               return_method = true);
 
   // virtual method calling
   void lookup_virtual_method(Register             recv_klass,
--- a/src/hotspot/cpu/s390/methodHandles_s390.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/cpu/s390/methodHandles_s390.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -498,7 +498,7 @@
       Label L_no_such_interface;
       __ lookup_interface_method(temp1_recv_klass, temp3_intf,
                                  // Note: next two args must be the same:
-                                 Z_index, Z_method, temp2, noreg,
+                                 Z_index, Z_method, temp2,
                                  L_no_such_interface);
       jump_from_method_handle(_masm, Z_method, temp2, Z_R0, for_compiler_entry);
 
--- a/src/hotspot/cpu/s390/sharedRuntime_s390.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/cpu/s390/sharedRuntime_s390.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -2660,9 +2660,9 @@
   Label skip_fixup;
   {
     Label ic_miss;
-    const int klass_offset         = oopDesc::klass_offset_in_bytes();
-    const int holder_klass_offset  = CompiledICHolder::holder_klass_offset();
-    const int holder_method_offset = CompiledICHolder::holder_method_offset();
+    const int klass_offset           = oopDesc::klass_offset_in_bytes();
+    const int holder_klass_offset    = CompiledICHolder::holder_klass_offset();
+    const int holder_metadata_offset = CompiledICHolder::holder_metadata_offset();
 
     // Out-of-line call to ic_miss handler.
     __ call_ic_miss_handler(ic_miss, 0x11, 0, Z_R1_scratch);
@@ -2691,7 +2691,7 @@
     // This def MUST MATCH code in gen_c2i_adapter!
     const Register code = Z_R11;
 
-    __ z_lg(Z_method, holder_method_offset, Z_method);
+    __ z_lg(Z_method, holder_metadata_offset, Z_method);
     __ load_and_test_long(Z_R0, method_(code));
     __ z_brne(ic_miss);  // Cache miss: call runtime to handle this.
 
--- a/src/hotspot/cpu/s390/templateTable_s390.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/cpu/s390/templateTable_s390.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -3557,66 +3557,67 @@
   transition(vtos, vtos);
 
   assert(byte_no == f1_byte, "use this argument");
-  Register interface = Z_tos;
-  Register index = Z_ARG3;
-  Register receiver = Z_tmp_1;
-  Register flags = Z_ARG5;
+  Register klass     = Z_ARG2,
+           method    = Z_ARG3,
+           interface = Z_ARG4,
+           flags     = Z_ARG5,
+           receiver  = Z_tmp_1;
 
   BLOCK_COMMENT("invokeinterface {");
 
-  // Destroys Z_ARG1 and Z_ARG2, thus use Z_ARG4 and copy afterwards.
-  prepare_invoke(byte_no, Z_ARG4, index,  // Get f1 klassOop, f2 itable index.
+  prepare_invoke(byte_no, interface, method,  // Get f1 klassOop, f2 itable index.
                  receiver, flags);
 
   // Z_R14 (== Z_bytecode) : return entry
 
-  __ z_lgr(interface, Z_ARG4);
-
   // Special case of invokeinterface called for virtual method of
   // java.lang.Object. See cpCacheOop.cpp for details.
   // This code isn't produced by javac, but could be produced by
   // another compliant java compiler.
-  Label notMethod;
+  NearLabel notMethod, no_such_interface, no_such_method;
   __ testbit(flags, ConstantPoolCacheEntry::is_forced_virtual_shift);
   __ z_brz(notMethod);
-  invokevirtual_helper(index, receiver, flags);
+  invokevirtual_helper(method, receiver, flags);
   __ bind(notMethod);
 
   // Get receiver klass into klass - also a null check.
-  Register klass = flags;
-
   __ restore_locals();
   __ load_klass(klass, receiver);
 
+  __ lookup_interface_method(klass, interface, noreg, noreg, /*temp*/Z_ARG1,
+                             no_such_interface, /*return_method=*/false);
+
   // Profile this call.
-  __ profile_virtual_call(klass, Z_ARG2/*mdp*/, Z_ARG4/*scratch*/);
-
-  NearLabel  no_such_interface, no_such_method;
-  Register   method = Z_tmp_2;
-
-  // TK 2010-08-24: save the index to Z_ARG4. needed in case of an error
-  //                in throw_AbstractMethodErrorByTemplateTable
-  __ z_lgr(Z_ARG4, index);
-  // TK 2011-03-24: copy also klass because it could be changed in
-  //                lookup_interface_method
-  __ z_lgr(Z_ARG2, klass);
-  __ lookup_interface_method(// inputs: rec. class, interface, itable index
-                              klass, interface, index,
-                              // outputs: method, scan temp. reg
-                              method, Z_tmp_2, Z_R1_scratch,
-                              no_such_interface);
+  __ profile_virtual_call(klass, Z_ARG1/*mdp*/, flags/*scratch*/);
+
+  // Find entry point to call.
+
+  // Get declaring interface class from method
+  __ z_lg(interface, Address(method, Method::const_offset()));
+  __ z_lg(interface, Address(interface, ConstMethod::constants_offset()));
+  __ z_lg(interface, Address(interface, ConstantPool::pool_holder_offset_in_bytes()));
+
+  // Get itable index from method
+  Register index   = receiver,
+           method2 = flags;
+  __ z_lgf(index, Address(method, Method::itable_index_offset()));
+  __ z_aghi(index, -Method::itable_index_max);
+  __ z_lcgr(index, index);
+
+  __ lookup_interface_method(klass, interface, index, method2, Z_tmp_2,
+                             no_such_interface);
 
   // Check for abstract method error.
   // Note: This should be done more efficiently via a throw_abstract_method_error
   // interpreter entry point and a conditional jump to it in case of a null
   // method.
-  __ compareU64_and_branch(method, (intptr_t) 0,
+  __ compareU64_and_branch(method2, (intptr_t) 0,
                             Assembler::bcondZero, no_such_method);
 
-  __ profile_arguments_type(Z_ARG3, method, Z_ARG5, true);
+  __ profile_arguments_type(Z_tmp_1, method2, Z_tmp_2, true);
 
   // Do the call.
-  __ jump_from_interpreted(method, Z_ARG5);
+  __ jump_from_interpreted(method2, Z_tmp_2);
   __ should_not_reach_here();
 
   // exception handling code follows...
@@ -3628,12 +3629,8 @@
   // Throw exception.
   __ restore_bcp();      // Bcp must be correct for exception handler   (was destroyed).
   __ restore_locals();   // Make sure locals pointer is correct as well (was destroyed).
-  // TK 2010-08-24: Call throw_AbstractMethodErrorByTemplateTable now with the
-  //                relevant information for generating a better error message
   __ call_VM(noreg,
-              CAST_FROM_FN_PTR(address,
-                               InterpreterRuntime::throw_AbstractMethodError),
-              Z_ARG2, interface, Z_ARG4);
+             CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_AbstractMethodError));
   // The call_VM checks for exception, so we should never return here.
   __ should_not_reach_here();
 
@@ -3642,12 +3639,8 @@
   // Throw exception.
   __ restore_bcp();      // Bcp must be correct for exception handler   (was destroyed).
   __ restore_locals();   // Make sure locals pointer is correct as well (was destroyed).
-  // TK 2010-08-24: Call throw_IncompatibleClassChangeErrorByTemplateTable now with the
-  //                relevant information for generating a better error message
   __ call_VM(noreg,
-             CAST_FROM_FN_PTR(address,
-                              InterpreterRuntime::throw_IncompatibleClassChangeError),
-             Z_ARG2, interface);
+             CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_IncompatibleClassChangeError));
   // The call_VM checks for exception, so we should never return here.
   __ should_not_reach_here();
 
--- a/src/hotspot/cpu/s390/vtableStubs_s390.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/cpu/s390/vtableStubs_s390.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,6 +1,6 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
- * Copyright (c) 2016 SAP SE. All rights reserved.
+ * Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017 SAP SE. 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,6 +28,7 @@
 #include "code/vtableStubs.hpp"
 #include "interp_masm_s390.hpp"
 #include "memory/resourceArea.hpp"
+#include "oops/compiledICHolder.hpp"
 #include "oops/instanceKlass.hpp"
 #include "oops/klassVtable.hpp"
 #include "runtime/sharedRuntime.hpp"
@@ -57,7 +58,6 @@
   ResourceMark    rm;
   CodeBuffer      cb(s->entry_point(), code_length);
   MacroAssembler *masm = new MacroAssembler(&cb);
-  address start_pc;
   int     padding_bytes = 0;
 
 #if (!defined(PRODUCT) && defined(COMPILER2))
@@ -144,9 +144,9 @@
   return s;
 }
 
-VtableStub* VtableStubs::create_itable_stub(int vtable_index) {
+VtableStub* VtableStubs::create_itable_stub(int itable_index) {
   const int   code_length = VtableStub::pd_code_size_limit(false);
-  VtableStub *s = new(code_length) VtableStub(false, vtable_index);
+  VtableStub *s = new(code_length) VtableStub(false, itable_index);
   if (s == NULL) { // Indicates OOM in the code cache.
     return NULL;
   }
@@ -154,7 +154,6 @@
   ResourceMark    rm;
   CodeBuffer      cb(s->entry_point(), code_length);
   MacroAssembler *masm = new MacroAssembler(&cb);
-  address start_pc;
   int     padding_bytes = 0;
 
 #if (!defined(PRODUCT) && defined(COMPILER2))
@@ -174,11 +173,9 @@
   // Entry arguments:
   //  Z_method: Interface
   //  Z_ARG1:   Receiver
-  const Register rcvr_klass = Z_tmp_1;    // Used to compute itable_entry_addr.
-                                          // Use extra reg to avoid re-load.
-  const Register vtable_len = Z_tmp_2;    // Used to compute itable_entry_addr.
-  const Register itable_entry_addr = Z_R1_scratch;
-  const Register itable_interface  = Z_R0_scratch;
+  NearLabel no_such_interface;
+  const Register rcvr_klass = Z_tmp_1,
+                 interface  = Z_tmp_2;
 
   // Get receiver klass.
   // Must do an explicit check if implicit checks are disabled.
@@ -186,50 +183,15 @@
   __ null_check(Z_ARG1, Z_R1_scratch, oopDesc::klass_offset_in_bytes());
   __ load_klass(rcvr_klass, Z_ARG1);
 
-  // Load start of itable entries into itable_entry.
-  __ z_llgf(vtable_len, Address(rcvr_klass, Klass::vtable_length_offset()));
-  __ z_sllg(vtable_len, vtable_len, exact_log2(vtableEntry::size_in_bytes()));
-
-  // Loop over all itable entries until desired interfaceOop(Rinterface) found.
-  const int vtable_base_offset = in_bytes(Klass::vtable_start_offset());
-  // Count unused bytes.
-  start_pc = __ pc();
-  __ add2reg_with_index(itable_entry_addr, vtable_base_offset + itableOffsetEntry::interface_offset_in_bytes(), rcvr_klass, vtable_len);
-  padding_bytes += 20 - (__ pc() - start_pc);
-
-  const int itable_offset_search_inc = itableOffsetEntry::size() * wordSize;
-  Label search;
-  __ bind(search);
+  // Receiver subtype check against REFC.
+  __ z_lg(interface, Address(Z_method, CompiledICHolder::holder_klass_offset()));
+  __ lookup_interface_method(rcvr_klass, interface, noreg,
+                             noreg, Z_R1, no_such_interface, /*return_method=*/ false);
 
-  // Handle IncompatibleClassChangeError in itable stubs.
-  // If the entry is NULL then we've reached the end of the table
-  // without finding the expected interface, so throw an exception.
-  NearLabel   throw_icce;
-  __ load_and_test_long(itable_interface, Address(itable_entry_addr));
-  __ z_bre(throw_icce); // Throw the exception out-of-line.
-  // Count unused bytes.
-  start_pc = __ pc();
-  __ add2reg(itable_entry_addr, itable_offset_search_inc);
-  padding_bytes += 20 - (__ pc() - start_pc);
-  __ z_cgr(itable_interface, Z_method);
-  __ z_brne(search);
-
-  // Entry found. Itable_entry_addr points to the subsequent entry (itable_offset_search_inc too far).
-  // Get offset of vtable for interface.
-
-  const Register vtable_offset = Z_R1_scratch;
-  const Register itable_method = rcvr_klass;   // Calculated before.
-
-  const int vtable_offset_offset = (itableOffsetEntry::offset_offset_in_bytes() -
-                                    itableOffsetEntry::interface_offset_in_bytes()) -
-                                   itable_offset_search_inc;
-  __ z_llgf(vtable_offset, vtable_offset_offset, itable_entry_addr);
-
-  // Compute itableMethodEntry and get method and entry point for compiler.
-  const int method_offset = (itableMethodEntry::size() * wordSize * vtable_index) +
-                            itableMethodEntry::method_offset_in_bytes();
-
-  __ z_lg(Z_method, method_offset, vtable_offset, itable_method);
+  // Get Method* and entrypoint for compiler
+  __ z_lg(interface, Address(Z_method, CompiledICHolder::holder_metadata_offset()));
+  __ lookup_interface_method(rcvr_klass, interface, itable_index,
+                             Z_method, Z_R1, no_such_interface, /*return_method=*/ true);
 
 #ifndef PRODUCT
   if (DebugVtables) {
@@ -244,13 +206,13 @@
   address ame_addr = __ pc();
   // Must do an explicit check if implicit checks are disabled.
   if (!ImplicitNullChecks) {
-    __ compare64_and_branch(Z_method, (intptr_t) 0, Assembler::bcondEqual, throw_icce);
+    __ compare64_and_branch(Z_method, (intptr_t) 0, Assembler::bcondEqual, no_such_interface);
   }
   __ z_lg(Z_R1_scratch, in_bytes(Method::from_compiled_offset()), Z_method);
   __ z_br(Z_R1_scratch);
 
   // Handle IncompatibleClassChangeError in itable stubs.
-  __ bind(throw_icce);
+  __ bind(no_such_interface);
   // Count unused bytes
   //                  worst case          actual size
   // We force resolving of the call site by jumping to
@@ -273,13 +235,12 @@
   if (CountCompiledCalls) {
     size += 6 * 4;
   }
-  if (is_vtable_stub) {
-    size += 52;
-  } else {
-    size += 104;
+  size += is_vtable_stub ? 36 : 140;
+  if (UseCompressedClassPointers) {
+    size += MacroAssembler::instr_size_for_decode_klass_not_null();
   }
-  if (Universe::narrow_klass_base() != NULL) {
-    size += 16; // A guess.
+  if (!ImplicitNullChecks) {
+    size += 36;
   }
   return size;
 }
--- a/src/hotspot/cpu/sparc/macroAssembler_sparc.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/cpu/sparc/macroAssembler_sparc.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -2058,9 +2058,10 @@
                                              Register method_result,
                                              Register scan_temp,
                                              Register sethi_temp,
-                                             Label& L_no_such_interface) {
+                                             Label& L_no_such_interface,
+                                             bool return_method) {
   assert_different_registers(recv_klass, intf_klass, method_result, scan_temp);
-  assert(itable_index.is_constant() || itable_index.as_register() == method_result,
+  assert(!return_method || itable_index.is_constant() || itable_index.as_register() == method_result,
          "caller must use same register for non-constant itable index as for method");
 
   Label L_no_such_interface_restore;
@@ -2092,11 +2093,13 @@
   add(scan_temp, itb_offset, scan_temp);
   add(recv_klass, scan_temp, scan_temp);
 
-  // Adjust recv_klass by scaled itable_index, so we can free itable_index.
-  RegisterOrConstant itable_offset = itable_index;
-  itable_offset = regcon_sll_ptr(itable_index, exact_log2(itableMethodEntry::size() * wordSize), itable_offset);
-  itable_offset = regcon_inc_ptr(itable_offset, itableMethodEntry::method_offset_in_bytes(), itable_offset);
-  add(recv_klass, ensure_simm13_or_reg(itable_offset, sethi_temp), recv_klass);
+  if (return_method) {
+    // Adjust recv_klass by scaled itable_index, so we can free itable_index.
+    RegisterOrConstant itable_offset = itable_index;
+    itable_offset = regcon_sll_ptr(itable_index, exact_log2(itableMethodEntry::size() * wordSize), itable_offset);
+    itable_offset = regcon_inc_ptr(itable_offset, itableMethodEntry::method_offset_in_bytes(), itable_offset);
+    add(recv_klass, ensure_simm13_or_reg(itable_offset, sethi_temp), recv_klass);
+  }
 
   // for (scan = klass->itable(); scan->interface() != NULL; scan += scan_step) {
   //   if (scan->interface() == intf) {
@@ -2131,12 +2134,14 @@
 
   bind(L_found_method);
 
-  // Got a hit.
-  int ito_offset = itableOffsetEntry::offset_offset_in_bytes();
-  // scan_temp[-scan_step] points to the vtable offset we need
-  ito_offset -= scan_step;
-  lduw(scan_temp, ito_offset, scan_temp);
-  ld_ptr(recv_klass, scan_temp, method_result);
+  if (return_method) {
+    // Got a hit.
+    int ito_offset = itableOffsetEntry::offset_offset_in_bytes();
+    // scan_temp[-scan_step] points to the vtable offset we need
+    ito_offset -= scan_step;
+    lduw(scan_temp, ito_offset, scan_temp);
+    ld_ptr(recv_klass, scan_temp, method_result);
+  }
 
   if (did_save) {
     Label L_done;
--- a/src/hotspot/cpu/sparc/macroAssembler_sparc.hpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/cpu/sparc/macroAssembler_sparc.hpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1277,7 +1277,8 @@
                                RegisterOrConstant itable_index,
                                Register method_result,
                                Register temp_reg, Register temp2_reg,
-                               Label& no_such_interface);
+                               Label& no_such_interface,
+                               bool return_method = true);
 
   // virtual method calling
   void lookup_virtual_method(Register recv_klass,
--- a/src/hotspot/cpu/sparc/sharedRuntime_sparc.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/cpu/sparc/sharedRuntime_sparc.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -904,7 +904,7 @@
 
     Label ok, ok2;
     __ brx(Assembler::equal, false, Assembler::pt, ok);
-    __ delayed()->ld_ptr(G5_method, CompiledICHolder::holder_method_offset(), G5_method);
+    __ delayed()->ld_ptr(G5_method, CompiledICHolder::holder_metadata_offset(), G5_method);
     __ jump_to(ic_miss, G3_scratch);
     __ delayed()->nop();
 
--- a/src/hotspot/cpu/sparc/templateTable_sparc.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/cpu/sparc/templateTable_sparc.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -3081,15 +3081,15 @@
   assert(byte_no == f1_byte, "use this argument");
 
   const Register Rinterface  = G1_scratch;
+  const Register Rmethod     = Lscratch;
   const Register Rret        = G3_scratch;
-  const Register Rindex      = Lscratch;
   const Register O0_recv     = O0;
   const Register O1_flags    = O1;
   const Register O2_Klass    = O2;
   const Register Rscratch    = G4_scratch;
   assert_different_registers(Rscratch, G5_method);
 
-  prepare_invoke(byte_no, Rinterface, Rret, Rindex, O0_recv, O1_flags);
+  prepare_invoke(byte_no, Rinterface, Rret, Rmethod, O0_recv, O1_flags);
 
   // get receiver klass
   __ null_check(O0_recv, oopDesc::klass_offset_in_bytes());
@@ -3109,55 +3109,40 @@
 
   __ bind(notMethod);
 
+  Register Rtemp = O1_flags;
+
+  Label L_no_such_interface;
+
+  // Receiver subtype check against REFC.
+  __ lookup_interface_method(// inputs: rec. class, interface, itable index
+                             O2_Klass, Rinterface, noreg,
+                             // outputs: temp reg1, temp reg2, temp reg3
+                             G5_method, Rscratch, Rtemp,
+                             L_no_such_interface,
+                             /*return_method=*/false);
+
   __ profile_virtual_call(O2_Klass, O4);
 
   //
   // find entry point to call
   //
 
-  // compute start of first itableOffsetEntry (which is at end of vtable)
-  const int base = in_bytes(Klass::vtable_start_offset());
-  Label search;
-  Register Rtemp = O1_flags;
-
-  __ ld(O2_Klass, in_bytes(Klass::vtable_length_offset()), Rtemp);
-  __ sll(Rtemp, LogBytesPerWord, Rtemp);   // Rscratch *= 4;
-  if (Assembler::is_simm13(base)) {
-    __ add(Rtemp, base, Rtemp);
-  } else {
-    __ set(base, Rscratch);
-    __ add(Rscratch, Rtemp, Rtemp);
-  }
-  __ add(O2_Klass, Rtemp, Rscratch);
-
-  __ bind(search);
-
-  __ ld_ptr(Rscratch, itableOffsetEntry::interface_offset_in_bytes(), Rtemp);
-  {
-    Label ok;
-
-    // Check that entry is non-null.  Null entries are probably a bytecode
-    // problem.  If the interface isn't implemented by the receiver class,
-    // the VM should throw IncompatibleClassChangeError.  linkResolver checks
-    // this too but that's only if the entry isn't already resolved, so we
-    // need to check again.
-    __ br_notnull_short( Rtemp, Assembler::pt, ok);
-    call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_IncompatibleClassChangeError));
-    __ should_not_reach_here();
-    __ bind(ok);
-  }
-
-  __ cmp(Rinterface, Rtemp);
-  __ brx(Assembler::notEqual, true, Assembler::pn, search);
-  __ delayed()->add(Rscratch, itableOffsetEntry::size() * wordSize, Rscratch);
-
-  // entry found and Rscratch points to it
-  __ ld(Rscratch, itableOffsetEntry::offset_offset_in_bytes(), Rscratch);
-
-  assert(itableMethodEntry::method_offset_in_bytes() == 0, "adjust instruction below");
-  __ sll(Rindex, exact_log2(itableMethodEntry::size() * wordSize), Rindex);       // Rindex *= 8;
-  __ add(Rscratch, Rindex, Rscratch);
-  __ ld_ptr(O2_Klass, Rscratch, G5_method);
+  // Get declaring interface class from method
+  __ ld_ptr(Rmethod, Method::const_offset(), Rinterface);
+  __ ld_ptr(Rinterface, ConstMethod::constants_offset(), Rinterface);
+  __ ld_ptr(Rinterface, ConstantPool::pool_holder_offset_in_bytes(), Rinterface);
+
+  // Get itable index from method
+  const Register Rindex = G5_method;
+  __ ld(Rmethod, Method::itable_index_offset(), Rindex);
+  __ sub(Rindex, Method::itable_index_max, Rindex);
+  __ neg(Rindex);
+
+  __ lookup_interface_method(// inputs: rec. class, interface, itable index
+                             O2_Klass, Rinterface, Rindex,
+                             // outputs: method, scan temp reg, temp reg
+                             G5_method, Rscratch, Rtemp,
+                             L_no_such_interface);
 
   // Check for abstract method error.
   {
@@ -3174,6 +3159,10 @@
   __ profile_arguments_type(G5_method, Rcall, Gargs, true);
   __ profile_called_method(G5_method, Rscratch);
   __ call_from_interpreter(Rcall, Gargs, Rret);
+
+  __ bind(L_no_such_interface);
+  call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_IncompatibleClassChangeError));
+  __ should_not_reach_here();
 }
 
 void TemplateTable::invokehandle(int byte_no) {
--- a/src/hotspot/cpu/sparc/vtableStubs_sparc.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/cpu/sparc/vtableStubs_sparc.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -27,6 +27,7 @@
 #include "code/vtableStubs.hpp"
 #include "interp_masm_sparc.hpp"
 #include "memory/resourceArea.hpp"
+#include "oops/compiledICHolder.hpp"
 #include "oops/instanceKlass.hpp"
 #include "oops/klassVtable.hpp"
 #include "runtime/sharedRuntime.hpp"
@@ -140,7 +141,8 @@
   MacroAssembler* masm = new MacroAssembler(&cb);
 
   Register G3_Klass = G3_scratch;
-  Register G5_interface = G5;  // Passed in as an argument
+  Register G5_icholder = G5;  // Passed in as an argument
+  Register G4_interface = G4_scratch;
   Label search;
 
   // Entry arguments:
@@ -164,14 +166,26 @@
   }
 #endif /* PRODUCT */
 
-  Label throw_icce;
+  Label L_no_such_interface;
 
   Register L5_method = L5;
+
+  // Receiver subtype check against REFC.
+  __ ld_ptr(G5_icholder, CompiledICHolder::holder_klass_offset(), G4_interface);
   __ lookup_interface_method(// inputs: rec. class, interface, itable index
-                             G3_Klass, G5_interface, itable_index,
+                             G3_Klass, G4_interface, itable_index,
+                             // outputs: scan temp. reg1, scan temp. reg2
+                             L5_method, L2, L3,
+                             L_no_such_interface,
+                             /*return_method=*/ false);
+
+  // Get Method* and entrypoint for compiler
+  __ ld_ptr(G5_icholder, CompiledICHolder::holder_metadata_offset(), G4_interface);
+  __ lookup_interface_method(// inputs: rec. class, interface, itable index
+                             G3_Klass, G4_interface, itable_index,
                              // outputs: method, scan temp. reg
                              L5_method, L2, L3,
-                             throw_icce);
+                             L_no_such_interface);
 
 #ifndef PRODUCT
   if (DebugVtables) {
@@ -197,7 +211,7 @@
   __ JMP(G3_scratch, 0);
   __ delayed()->nop();
 
-  __ bind(throw_icce);
+  __ bind(L_no_such_interface);
   AddressLiteral icce(StubRoutines::throw_IncompatibleClassChangeError_entry());
   __ jump_to(icce, G3_scratch);
   __ delayed()->restore();
@@ -232,7 +246,7 @@
                           MacroAssembler::instr_size_for_decode_klass_not_null() : 0);
       return basic + slop;
     } else {
-      const int basic = 34 * BytesPerInstWord +
+      const int basic = 54 * BytesPerInstWord +
                         // shift;add for load_klass (only shift with zero heap based)
                         (UseCompressedClassPointers ?
                           MacroAssembler::instr_size_for_decode_klass_not_null() : 0);
--- a/src/hotspot/cpu/x86/macroAssembler_x86.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/cpu/x86/macroAssembler_x86.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -5809,8 +5809,13 @@
                                              RegisterOrConstant itable_index,
                                              Register method_result,
                                              Register scan_temp,
-                                             Label& L_no_such_interface) {
-  assert_different_registers(recv_klass, intf_klass, method_result, scan_temp);
+                                             Label& L_no_such_interface,
+                                             bool return_method) {
+  assert_different_registers(recv_klass, intf_klass, scan_temp);
+  assert_different_registers(method_result, intf_klass, scan_temp);
+  assert(recv_klass != method_result || !return_method,
+         "recv_klass can be destroyed when method isn't needed");
+
   assert(itable_index.is_constant() || itable_index.as_register() == method_result,
          "caller must use same register for non-constant itable index as for method");
 
@@ -5827,9 +5832,11 @@
   // %%% Could store the aligned, prescaled offset in the klassoop.
   lea(scan_temp, Address(recv_klass, scan_temp, times_vte_scale, vtable_base));
 
-  // Adjust recv_klass by scaled itable_index, so we can free itable_index.
-  assert(itableMethodEntry::size() * wordSize == wordSize, "adjust the scaling in the code below");
-  lea(recv_klass, Address(recv_klass, itable_index, Address::times_ptr, itentry_off));
+  if (return_method) {
+    // Adjust recv_klass by scaled itable_index, so we can free itable_index.
+    assert(itableMethodEntry::size() * wordSize == wordSize, "adjust the scaling in the code below");
+    lea(recv_klass, Address(recv_klass, itable_index, Address::times_ptr, itentry_off));
+  }
 
   // for (scan = klass->itable(); scan->interface() != NULL; scan += scan_step) {
   //   if (scan->interface() == intf) {
@@ -5863,9 +5870,11 @@
 
   bind(found_method);
 
-  // Got a hit.
-  movl(scan_temp, Address(scan_temp, itableOffsetEntry::offset_offset_in_bytes()));
-  movptr(method_result, Address(recv_klass, scan_temp, Address::times_1));
+  if (return_method) {
+    // Got a hit.
+    movl(scan_temp, Address(scan_temp, itableOffsetEntry::offset_offset_in_bytes()));
+    movptr(method_result, Address(recv_klass, scan_temp, Address::times_1));
+  }
 }
 
 
--- a/src/hotspot/cpu/x86/macroAssembler_x86.hpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/cpu/x86/macroAssembler_x86.hpp	Fri Jan 19 09:32:10 2018 -0800
@@ -544,7 +544,8 @@
                                RegisterOrConstant itable_index,
                                Register method_result,
                                Register scan_temp,
-                               Label& no_such_interface);
+                               Label& no_such_interface,
+                               bool return_method = true);
 
   // virtual method calling
   void lookup_virtual_method(Register recv_klass,
--- a/src/hotspot/cpu/x86/sharedRuntime_x86_32.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/cpu/x86/sharedRuntime_x86_32.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -957,7 +957,7 @@
     Label missed;
     __ movptr(temp, Address(receiver, oopDesc::klass_offset_in_bytes()));
     __ cmpptr(temp, Address(holder, CompiledICHolder::holder_klass_offset()));
-    __ movptr(rbx, Address(holder, CompiledICHolder::holder_method_offset()));
+    __ movptr(rbx, Address(holder, CompiledICHolder::holder_metadata_offset()));
     __ jcc(Assembler::notEqual, missed);
     // Method might have been compiled since the call site was patched to
     // interpreted if that is the case treat it as a miss so we can get
--- a/src/hotspot/cpu/x86/sharedRuntime_x86_64.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/cpu/x86/sharedRuntime_x86_64.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -949,7 +949,7 @@
   {
     __ load_klass(temp, receiver);
     __ cmpptr(temp, Address(holder, CompiledICHolder::holder_klass_offset()));
-    __ movptr(rbx, Address(holder, CompiledICHolder::holder_method_offset()));
+    __ movptr(rbx, Address(holder, CompiledICHolder::holder_metadata_offset()));
     __ jcc(Assembler::equal, ok);
     __ jump(RuntimeAddress(SharedRuntime::get_ic_miss_stub()));
 
--- a/src/hotspot/cpu/x86/templateTable_x86.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/cpu/x86/templateTable_x86.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -3712,11 +3712,11 @@
 void TemplateTable::invokeinterface(int byte_no) {
   transition(vtos, vtos);
   assert(byte_no == f1_byte, "use this argument");
-  prepare_invoke(byte_no, rax, rbx,  // get f1 Klass*, f2 itable index
+  prepare_invoke(byte_no, rax, rbx,  // get f1 Klass*, f2 Method*
                  rcx, rdx); // recv, flags
 
-  // rax: interface klass (from f1)
-  // rbx: itable index (from f2)
+  // rax: reference klass (from f1)
+  // rbx: method (from f2)
   // rcx: receiver
   // rdx: flags
 
@@ -3738,10 +3738,28 @@
   __ null_check(rcx, oopDesc::klass_offset_in_bytes());
   __ load_klass(rdx, rcx);
 
+  Label no_such_interface, no_such_method;
+
+  // Receiver subtype check against REFC.
+  // Superklass in rax. Subklass in rdx. Blows rcx, rdi.
+  __ lookup_interface_method(// inputs: rec. class, interface, itable index
+                             rdx, rax, noreg,
+                             // outputs: scan temp. reg, scan temp. reg
+                             rbcp, rlocals,
+                             no_such_interface,
+                             /*return_method=*/false);
+
   // profile this call
+  __ restore_bcp(); // rbcp was destroyed by receiver type check
   __ profile_virtual_call(rdx, rbcp, rlocals);
 
-  Label no_such_interface, no_such_method;
+  // Get declaring interface class from method, and itable index
+  __ movptr(rax, Address(rbx, Method::const_offset()));
+  __ movptr(rax, Address(rax, ConstMethod::constants_offset()));
+  __ movptr(rax, Address(rax, ConstantPool::pool_holder_offset_in_bytes()));
+  __ movl(rbx, Address(rbx, Method::itable_index_offset()));
+  __ subl(rbx, Method::itable_index_max);
+  __ negl(rbx);
 
   __ lookup_interface_method(// inputs: rec. class, interface, itable index
                              rdx, rax, rbx,
--- a/src/hotspot/cpu/x86/vtableStubs_x86_32.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/cpu/x86/vtableStubs_x86_32.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -27,6 +27,7 @@
 #include "code/vtableStubs.hpp"
 #include "interp_masm_x86.hpp"
 #include "memory/resourceArea.hpp"
+#include "oops/compiledICHolder.hpp"
 #include "oops/instanceKlass.hpp"
 #include "oops/klassVtable.hpp"
 #include "runtime/sharedRuntime.hpp"
@@ -147,7 +148,7 @@
   MacroAssembler* masm = new MacroAssembler(&cb);
 
   // Entry arguments:
-  //  rax,: Interface
+  //  rax: CompiledICHolder
   //  rcx: Receiver
 
 #ifndef PRODUCT
@@ -155,25 +156,42 @@
     __ incrementl(ExternalAddress((address) SharedRuntime::nof_megamorphic_calls_addr()));
   }
 #endif /* PRODUCT */
-  // get receiver (need to skip return address on top of stack)
-
-  assert(VtableStub::receiver_location() == rcx->as_VMReg(), "receiver expected in rcx");
-
-  // get receiver klass (also an implicit null-check)
-  address npe_addr = __ pc();
-  __ movptr(rsi, Address(rcx, oopDesc::klass_offset_in_bytes()));
 
   // Most registers are in use; we'll use rax, rbx, rsi, rdi
   // (If we need to make rsi, rdi callee-save, do a push/pop here.)
+  const Register recv_klass_reg     = rsi;
+  const Register holder_klass_reg   = rax; // declaring interface klass (DECC)
+  const Register resolved_klass_reg = rbx; // resolved interface klass (REFC)
+  const Register temp_reg           = rdi;
+
+  const Register icholder_reg = rax;
+  __ movptr(resolved_klass_reg, Address(icholder_reg, CompiledICHolder::holder_klass_offset()));
+  __ movptr(holder_klass_reg,   Address(icholder_reg, CompiledICHolder::holder_metadata_offset()));
+
+  Label L_no_such_interface;
+
+  // get receiver klass (also an implicit null-check)
+  address npe_addr = __ pc();
+  assert(VtableStub::receiver_location() ==  rcx->as_VMReg(), "receiver expected in  rcx");
+  __ load_klass(recv_klass_reg, rcx);
+
+  // Receiver subtype check against REFC.
+  // Destroys recv_klass_reg value.
+  __ lookup_interface_method(// inputs: rec. class, interface
+                             recv_klass_reg, resolved_klass_reg, noreg,
+                             // outputs:  scan temp. reg1, scan temp. reg2
+                             recv_klass_reg, temp_reg,
+                             L_no_such_interface,
+                             /*return_method=*/false);
+
+  // Get selected method from declaring class and itable index
   const Register method = rbx;
-  Label throw_icce;
-
-  // Get Method* and entrypoint for compiler
+  __ load_klass(recv_klass_reg, rcx); // restore recv_klass_reg
   __ lookup_interface_method(// inputs: rec. class, interface, itable index
-                             rsi, rax, itable_index,
+                             recv_klass_reg, holder_klass_reg, itable_index,
                              // outputs: method, scan temp. reg
-                             method, rdi,
-                             throw_icce);
+                             method, temp_reg,
+                             L_no_such_interface);
 
   // method (rbx): Method*
   // rcx: receiver
@@ -193,9 +211,10 @@
   address ame_addr = __ pc();
   __ jmp(Address(method, Method::from_compiled_offset()));
 
-  __ bind(throw_icce);
+  __ bind(L_no_such_interface);
   __ jump(RuntimeAddress(StubRoutines::throw_IncompatibleClassChangeError_entry()));
-  masm->flush();
+
+  __ flush();
 
   if (PrintMiscellaneous && (WizardMode || Verbose)) {
     tty->print_cr("itable #%d at " PTR_FORMAT "[%d] left over: %d",
@@ -220,7 +239,7 @@
     return (DebugVtables ? 210 : 16) + (CountCompiledCalls ? 6 : 0);
   } else {
     // Itable stub size
-    return (DebugVtables ? 256 : 66) + (CountCompiledCalls ? 6 : 0);
+    return (DebugVtables ? 256 : 110) + (CountCompiledCalls ? 6 : 0);
   }
   // In order to tune these parameters, run the JVM with VM options
   // +PrintMiscellaneous and +WizardMode to see information about
--- a/src/hotspot/cpu/x86/vtableStubs_x86_64.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/cpu/x86/vtableStubs_x86_64.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -27,6 +27,7 @@
 #include "code/vtableStubs.hpp"
 #include "interp_masm_x86.hpp"
 #include "memory/resourceArea.hpp"
+#include "oops/compiledICHolder.hpp"
 #include "oops/instanceKlass.hpp"
 #include "oops/klassVtable.hpp"
 #include "runtime/sharedRuntime.hpp"
@@ -147,36 +148,50 @@
 #endif
 
   // Entry arguments:
-  //  rax: Interface
+  //  rax: CompiledICHolder
   //  j_rarg0: Receiver
 
-  // Free registers (non-args) are rax (interface), rbx
-
-  // get receiver (need to skip return address on top of stack)
-
-  assert(VtableStub::receiver_location() == j_rarg0->as_VMReg(), "receiver expected in j_rarg0");
-  // get receiver klass (also an implicit null-check)
-  address npe_addr = __ pc();
-
   // Most registers are in use; we'll use rax, rbx, r10, r11
   // (various calling sequences use r[cd]x, r[sd]i, r[89]; stay away from them)
-  __ load_klass(r10, j_rarg0);
+  const Register recv_klass_reg     = r10;
+  const Register holder_klass_reg   = rax; // declaring interface klass (DECC)
+  const Register resolved_klass_reg = rbx; // resolved interface klass (REFC)
+  const Register temp_reg           = r11;
+
+  Label L_no_such_interface;
+
+  const Register icholder_reg = rax;
+  __ movptr(resolved_klass_reg, Address(icholder_reg, CompiledICHolder::holder_klass_offset()));
+  __ movptr(holder_klass_reg,   Address(icholder_reg, CompiledICHolder::holder_metadata_offset()));
+
+  // get receiver klass (also an implicit null-check)
+  assert(VtableStub::receiver_location() == j_rarg0->as_VMReg(), "receiver expected in j_rarg0");
+  address npe_addr = __ pc();
+  __ load_klass(recv_klass_reg, j_rarg0);
+
+  // Receiver subtype check against REFC.
+  // Destroys recv_klass_reg value.
+  __ lookup_interface_method(// inputs: rec. class, interface
+                             recv_klass_reg, resolved_klass_reg, noreg,
+                             // outputs:  scan temp. reg1, scan temp. reg2
+                             recv_klass_reg, temp_reg,
+                             L_no_such_interface,
+                             /*return_method=*/false);
+
+  // Get selected method from declaring class and itable index
+  const Register method = rbx;
+  __ load_klass(recv_klass_reg, j_rarg0);   // restore recv_klass_reg
+  __ lookup_interface_method(// inputs: rec. class, interface, itable index
+                       recv_klass_reg, holder_klass_reg, itable_index,
+                       // outputs: method, scan temp. reg
+                       method, temp_reg,
+                       L_no_such_interface);
 
   // If we take a trap while this arg is on the stack we will not
   // be able to walk the stack properly. This is not an issue except
   // when there are mistakes in this assembly code that could generate
   // a spurious fault. Ask me how I know...
 
-  const Register method = rbx;
-  Label throw_icce;
-
-  // Get Method* and entrypoint for compiler
-  __ lookup_interface_method(// inputs: rec. class, interface, itable index
-                             r10, rax, itable_index,
-                             // outputs: method, scan temp. reg
-                             method, r11,
-                             throw_icce);
-
   // method (rbx): Method*
   // j_rarg0: receiver
 
@@ -197,7 +212,7 @@
   address ame_addr = __ pc();
   __ jmp(Address(method, Method::from_compiled_offset()));
 
-  __ bind(throw_icce);
+  __ bind(L_no_such_interface);
   __ jump(RuntimeAddress(StubRoutines::throw_IncompatibleClassChangeError_entry()));
 
   __ flush();
@@ -224,8 +239,8 @@
            (UseCompressedClassPointers ?  MacroAssembler::instr_size_for_decode_klass_not_null() : 0);
   } else {
     // Itable stub size
-    return (DebugVtables ? 512 : 74) + (CountCompiledCalls ? 13 : 0) +
-           (UseCompressedClassPointers ?  MacroAssembler::instr_size_for_decode_klass_not_null() : 0);
+    return (DebugVtables ? 512 : 140) + (CountCompiledCalls ? 13 : 0) +
+           (UseCompressedClassPointers ? 2 * MacroAssembler::instr_size_for_decode_klass_not_null() : 0);
   }
   // In order to tune these parameters, run the JVM with VM options
   // +PrintMiscellaneous and +WizardMode to see information about
--- a/src/hotspot/os/aix/os_aix.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/os/aix/os_aix.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2018, Oracle and/or its affiliates. All rights reserved.
  * Copyright (c) 2012, 2017 SAP SE. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
@@ -1723,7 +1723,7 @@
   local_sem_post();
 }
 
-static int check_pending_signals(bool wait) {
+static int check_pending_signals() {
   Atomic::store(0, &sigint_count);
   for (;;) {
     for (int i = 0; i < NSIG + 1; i++) {
@@ -1732,9 +1732,6 @@
         return i;
       }
     }
-    if (!wait) {
-      return -1;
-    }
     JavaThread *thread = JavaThread::current();
     ThreadBlockInVM tbivm(thread);
 
@@ -1763,12 +1760,8 @@
   }
 }
 
-int os::signal_lookup() {
-  return check_pending_signals(false);
-}
-
 int os::signal_wait() {
-  return check_pending_signals(true);
+  return check_pending_signals();
 }
 
 ////////////////////////////////////////////////////////////////////////////////
--- a/src/hotspot/os/bsd/os_bsd.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/os/bsd/os_bsd.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2018, 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
@@ -52,13 +52,13 @@
 #include "runtime/orderAccess.inline.hpp"
 #include "runtime/osThread.hpp"
 #include "runtime/perfMemory.hpp"
+#include "runtime/semaphore.hpp"
 #include "runtime/sharedRuntime.hpp"
 #include "runtime/statSampler.hpp"
 #include "runtime/stubRoutines.hpp"
 #include "runtime/thread.inline.hpp"
 #include "runtime/threadCritical.hpp"
 #include "runtime/timer.hpp"
-#include "semaphore_bsd.hpp"
 #include "services/attachListener.hpp"
 #include "services/memTracker.hpp"
 #include "services/runtimeService.hpp"
@@ -91,7 +91,6 @@
 # include <time.h>
 # include <pwd.h>
 # include <poll.h>
-# include <semaphore.h>
 # include <fcntl.h>
 # include <string.h>
 # include <sys/param.h>
@@ -1829,135 +1828,28 @@
 
 // a counter for each possible signal value
 static volatile jint pending_signals[NSIG+1] = { 0 };
-
-// Bsd(POSIX) specific hand shaking semaphore.
-#ifdef __APPLE__
-typedef semaphore_t os_semaphore_t;
-
-  #define SEM_INIT(sem, value)    semaphore_create(mach_task_self(), &sem, SYNC_POLICY_FIFO, value)
-  #define SEM_WAIT(sem)           semaphore_wait(sem)
-  #define SEM_POST(sem)           semaphore_signal(sem)
-  #define SEM_DESTROY(sem)        semaphore_destroy(mach_task_self(), sem)
-#else
-typedef sem_t os_semaphore_t;
-
-  #define SEM_INIT(sem, value)    sem_init(&sem, 0, value)
-  #define SEM_WAIT(sem)           sem_wait(&sem)
-  #define SEM_POST(sem)           sem_post(&sem)
-  #define SEM_DESTROY(sem)        sem_destroy(&sem)
-#endif
-
-#ifdef __APPLE__
-// OS X doesn't support unamed POSIX semaphores, so the implementation in os_posix.cpp can't be used.
-
-static const char* sem_init_strerror(kern_return_t value) {
-  switch (value) {
-    case KERN_INVALID_ARGUMENT:  return "Invalid argument";
-    case KERN_RESOURCE_SHORTAGE: return "Resource shortage";
-    default:                     return "Unknown";
-  }
-}
-
-OSXSemaphore::OSXSemaphore(uint value) {
-  kern_return_t ret = SEM_INIT(_semaphore, value);
-
-  guarantee(ret == KERN_SUCCESS, "Failed to create semaphore: %s", sem_init_strerror(ret));
-}
-
-OSXSemaphore::~OSXSemaphore() {
-  SEM_DESTROY(_semaphore);
-}
-
-void OSXSemaphore::signal(uint count) {
-  for (uint i = 0; i < count; i++) {
-    kern_return_t ret = SEM_POST(_semaphore);
-
-    assert(ret == KERN_SUCCESS, "Failed to signal semaphore");
-  }
-}
-
-void OSXSemaphore::wait() {
-  kern_return_t ret;
-  while ((ret = SEM_WAIT(_semaphore)) == KERN_ABORTED) {
-    // Semaphore was interrupted. Retry.
-  }
-  assert(ret == KERN_SUCCESS, "Failed to wait on semaphore");
-}
-
-jlong OSXSemaphore::currenttime() {
-  struct timeval tv;
-  gettimeofday(&tv, NULL);
-  return (tv.tv_sec * NANOSECS_PER_SEC) + (tv.tv_usec * 1000);
-}
-
-bool OSXSemaphore::trywait() {
-  return timedwait(0, 0);
-}
-
-bool OSXSemaphore::timedwait(unsigned int sec, int nsec) {
-  kern_return_t kr = KERN_ABORTED;
-  mach_timespec_t waitspec;
-  waitspec.tv_sec = sec;
-  waitspec.tv_nsec = nsec;
-
-  jlong starttime = currenttime();
-
-  kr = semaphore_timedwait(_semaphore, waitspec);
-  while (kr == KERN_ABORTED) {
-    jlong totalwait = (sec * NANOSECS_PER_SEC) + nsec;
-
-    jlong current = currenttime();
-    jlong passedtime = current - starttime;
-
-    if (passedtime >= totalwait) {
-      waitspec.tv_sec = 0;
-      waitspec.tv_nsec = 0;
-    } else {
-      jlong waittime = totalwait - (current - starttime);
-      waitspec.tv_sec = waittime / NANOSECS_PER_SEC;
-      waitspec.tv_nsec = waittime % NANOSECS_PER_SEC;
-    }
-
-    kr = semaphore_timedwait(_semaphore, waitspec);
-  }
-
-  return kr == KERN_SUCCESS;
-}
-
-#else
-// Use POSIX implementation of semaphores.
-
-struct timespec PosixSemaphore::create_timespec(unsigned int sec, int nsec) {
-  struct timespec ts;
-  unpackTime(&ts, false, (sec * NANOSECS_PER_SEC) + nsec);
-
-  return ts;
-}
-
-#endif // __APPLE__
-
-static os_semaphore_t sig_sem;
-
-#ifdef __APPLE__
-static OSXSemaphore sr_semaphore;
-#else
-static PosixSemaphore sr_semaphore;
-#endif
+static Semaphore* sig_sem = NULL;
 
 void os::signal_init_pd() {
   // Initialize signal structures
   ::memset((void*)pending_signals, 0, sizeof(pending_signals));
 
   // Initialize signal semaphore
-  ::SEM_INIT(sig_sem, 0);
+  sig_sem = new Semaphore();
 }
 
 void os::signal_notify(int sig) {
-  Atomic::inc(&pending_signals[sig]);
-  ::SEM_POST(sig_sem);
+  if (sig_sem != NULL) {
+    Atomic::inc(&pending_signals[sig]);
+    sig_sem->signal();
+  } else {
+    // Signal thread is not created with ReduceSignalUsage and signal_init_pd
+    // initialization isn't called.
+    assert(ReduceSignalUsage, "signal semaphore should be created");
+  }
 }
 
-static int check_pending_signals(bool wait) {
+static int check_pending_signals() {
   Atomic::store(0, &sigint_count);
   for (;;) {
     for (int i = 0; i < NSIG + 1; i++) {
@@ -1966,9 +1858,6 @@
         return i;
       }
     }
-    if (!wait) {
-      return -1;
-    }
     JavaThread *thread = JavaThread::current();
     ThreadBlockInVM tbivm(thread);
 
@@ -1976,7 +1865,7 @@
     do {
       thread->set_suspend_equivalent();
       // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self()
-      ::SEM_WAIT(sig_sem);
+      sig_sem->wait();
 
       // were we externally suspended while we were waiting?
       threadIsSuspended = thread->handle_special_suspend_equivalent_condition();
@@ -1985,7 +1874,7 @@
         // another thread suspended us. We don't want to continue running
         // while suspended because that would surprise the thread that
         // suspended us.
-        ::SEM_POST(sig_sem);
+        sig_sem->signal();
 
         thread->java_suspend_self();
       }
@@ -1993,12 +1882,8 @@
   }
 }
 
-int os::signal_lookup() {
-  return check_pending_signals(false);
-}
-
 int os::signal_wait() {
-  return check_pending_signals(true);
+  return check_pending_signals();
 }
 
 ////////////////////////////////////////////////////////////////////////////////
@@ -2663,6 +2548,12 @@
 //
 // Currently only ever called on the VMThread or JavaThread
 //
+#ifdef __APPLE__
+static OSXSemaphore sr_semaphore;
+#else
+static PosixSemaphore sr_semaphore;
+#endif
+
 static void SR_handler(int sig, siginfo_t* siginfo, ucontext_t* context) {
   // Save and restore errno to avoid confusing native code with EINTR
   // after sigsuspend.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/hotspot/os/bsd/semaphore_bsd.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -0,0 +1,107 @@
+/*
+ * Copyright (c) 2018, 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.
+ *
+ */
+
+#include "precompiled/precompiled.hpp"
+#include "semaphore_bsd.hpp"
+#include "utilities/debug.hpp"
+
+#include <semaphore.h>
+
+#ifdef __APPLE__
+// OS X doesn't support unamed POSIX semaphores, so the implementation in os_posix.cpp can't be used.
+
+static const char* sem_init_strerror(kern_return_t value) {
+  switch (value) {
+    case KERN_INVALID_ARGUMENT:  return "Invalid argument";
+    case KERN_RESOURCE_SHORTAGE: return "Resource shortage";
+    default:                     return "Unknown";
+  }
+}
+
+OSXSemaphore::OSXSemaphore(uint value) {
+  kern_return_t ret = semaphore_create(mach_task_self(), &_semaphore, SYNC_POLICY_FIFO, value);
+
+  guarantee(ret == KERN_SUCCESS, "Failed to create semaphore: %s", sem_init_strerror(ret));
+}
+
+OSXSemaphore::~OSXSemaphore() {
+  semaphore_destroy(mach_task_self(), _semaphore);
+}
+
+void OSXSemaphore::signal(uint count) {
+  for (uint i = 0; i < count; i++) {
+    kern_return_t ret = semaphore_signal(_semaphore);
+
+    assert(ret == KERN_SUCCESS, "Failed to signal semaphore");
+  }
+}
+
+void OSXSemaphore::wait() {
+  kern_return_t ret;
+  while ((ret = semaphore_wait(_semaphore)) == KERN_ABORTED) {
+    // Semaphore was interrupted. Retry.
+  }
+  assert(ret == KERN_SUCCESS, "Failed to wait on semaphore");
+}
+
+int64_t OSXSemaphore::currenttime() {
+  struct timeval tv;
+  gettimeofday(&tv, NULL);
+  return (tv.tv_sec * NANOSECS_PER_SEC) + (tv.tv_usec * 1000);
+}
+
+bool OSXSemaphore::trywait() {
+  return timedwait(0, 0);
+}
+
+bool OSXSemaphore::timedwait(unsigned int sec, int nsec) {
+  kern_return_t kr = KERN_ABORTED;
+  mach_timespec_t waitspec;
+  waitspec.tv_sec = sec;
+  waitspec.tv_nsec = nsec;
+
+  int64_t starttime = currenttime();
+
+  kr = semaphore_timedwait(_semaphore, waitspec);
+  while (kr == KERN_ABORTED) {
+    int64_t totalwait = (sec * NANOSECS_PER_SEC) + nsec;
+
+    int64_t current = currenttime();
+    int64_t passedtime = current - starttime;
+
+    if (passedtime >= totalwait) {
+      waitspec.tv_sec = 0;
+      waitspec.tv_nsec = 0;
+    } else {
+      int64_t waittime = totalwait - (current - starttime);
+      waitspec.tv_sec = waittime / NANOSECS_PER_SEC;
+      waitspec.tv_nsec = waittime % NANOSECS_PER_SEC;
+    }
+
+    kr = semaphore_timedwait(_semaphore, waitspec);
+  }
+
+  return kr == KERN_SUCCESS;
+}
+#endif // __APPLE__
--- a/src/hotspot/os/bsd/semaphore_bsd.hpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/os/bsd/semaphore_bsd.hpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -53,7 +53,7 @@
   bool timedwait(unsigned int sec, int nsec);
 
  private:
-  static jlong currenttime();
+  static int64_t currenttime();
 };
 
 typedef OSXSemaphore SemaphoreImpl;
--- a/src/hotspot/os/linux/os_linux.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/os/linux/os_linux.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -95,7 +95,6 @@
 # include <sys/wait.h>
 # include <pwd.h>
 # include <poll.h>
-# include <semaphore.h>
 # include <fcntl.h>
 # include <string.h>
 # include <syscall.h>
@@ -2479,11 +2478,11 @@
   return CAST_FROM_FN_PTR(void*, UserHandler);
 }
 
-struct timespec PosixSemaphore::create_timespec(unsigned int sec, int nsec) {
+static struct timespec create_semaphore_timespec(unsigned int sec, int nsec) {
   struct timespec ts;
   // Semaphore's are always associated with CLOCK_REALTIME
   os::Linux::clock_gettime(CLOCK_REALTIME, &ts);
-  // see unpackTime for discussion on overflow checking
+  // see os_posix.cpp for discussion on overflow checking
   if (sec >= MAX_SECS) {
     ts.tv_sec += MAX_SECS;
     ts.tv_nsec = 0;
@@ -2535,7 +2534,7 @@
 static volatile jint pending_signals[NSIG+1] = { 0 };
 
 // Linux(POSIX) specific hand shaking semaphore.
-static sem_t sig_sem;
+static Semaphore* sig_sem = NULL;
 static PosixSemaphore sr_semaphore;
 
 void os::signal_init_pd() {
@@ -2543,15 +2542,21 @@
   ::memset((void*)pending_signals, 0, sizeof(pending_signals));
 
   // Initialize signal semaphore
-  ::sem_init(&sig_sem, 0, 0);
+  sig_sem = new Semaphore();
 }
 
 void os::signal_notify(int sig) {
-  Atomic::inc(&pending_signals[sig]);
-  ::sem_post(&sig_sem);
-}
-
-static int check_pending_signals(bool wait) {
+  if (sig_sem != NULL) {
+    Atomic::inc(&pending_signals[sig]);
+    sig_sem->signal();
+  } else {
+    // Signal thread is not created with ReduceSignalUsage and signal_init_pd
+    // initialization isn't called.
+    assert(ReduceSignalUsage, "signal semaphore should be created");
+  }
+}
+
+static int check_pending_signals() {
   Atomic::store(0, &sigint_count);
   for (;;) {
     for (int i = 0; i < NSIG + 1; i++) {
@@ -2560,9 +2565,6 @@
         return i;
       }
     }
-    if (!wait) {
-      return -1;
-    }
     JavaThread *thread = JavaThread::current();
     ThreadBlockInVM tbivm(thread);
 
@@ -2570,7 +2572,7 @@
     do {
       thread->set_suspend_equivalent();
       // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self()
-      ::sem_wait(&sig_sem);
+      sig_sem->wait();
 
       // were we externally suspended while we were waiting?
       threadIsSuspended = thread->handle_special_suspend_equivalent_condition();
@@ -2579,7 +2581,7 @@
         // another thread suspended us. We don't want to continue running
         // while suspended because that would surprise the thread that
         // suspended us.
-        ::sem_post(&sig_sem);
+        sig_sem->signal();
 
         thread->java_suspend_self();
       }
@@ -2587,12 +2589,8 @@
   }
 }
 
-int os::signal_lookup() {
-  return check_pending_signals(false);
-}
-
 int os::signal_wait() {
-  return check_pending_signals(true);
+  return check_pending_signals();
 }
 
 ////////////////////////////////////////////////////////////////////////////////
@@ -4317,7 +4315,7 @@
 
   // managed to send the signal and switch to SUSPEND_REQUEST, now wait for SUSPENDED
   while (true) {
-    if (sr_semaphore.timedwait(0, 2 * NANOSECS_PER_MILLISEC)) {
+    if (sr_semaphore.timedwait(create_semaphore_timespec(0, 2 * NANOSECS_PER_MILLISEC))) {
       break;
     } else {
       // timeout
@@ -4351,7 +4349,7 @@
 
   while (true) {
     if (sr_notify(osthread) == 0) {
-      if (sr_semaphore.timedwait(0, 2 * NANOSECS_PER_MILLISEC)) {
+      if (sr_semaphore.timedwait(create_semaphore_timespec(0, 2 * NANOSECS_PER_MILLISEC))) {
         if (osthread->sr.is_running()) {
           return;
         }
--- a/src/hotspot/os/posix/os_posix.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/os/posix/os_posix.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2018, 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
@@ -31,14 +31,8 @@
 #include "utilities/macros.hpp"
 #include "utilities/vmError.hpp"
 
-#ifndef __APPLE__
-// POSIX unamed semaphores are not supported on OS X.
-#include "semaphore_posix.hpp"
-#endif
-
 #include <dlfcn.h>
 #include <pthread.h>
-#include <semaphore.h>
 #include <signal.h>
 #include <sys/mman.h>
 #include <sys/resource.h>
@@ -1499,67 +1493,6 @@
   }
 }
 
-// POSIX unamed semaphores are not supported on OS X.
-#ifndef __APPLE__
-
-PosixSemaphore::PosixSemaphore(uint value) {
-  int ret = sem_init(&_semaphore, 0, value);
-
-  guarantee_with_errno(ret == 0, "Failed to initialize semaphore");
-}
-
-PosixSemaphore::~PosixSemaphore() {
-  sem_destroy(&_semaphore);
-}
-
-void PosixSemaphore::signal(uint count) {
-  for (uint i = 0; i < count; i++) {
-    int ret = sem_post(&_semaphore);
-
-    assert_with_errno(ret == 0, "sem_post failed");
-  }
-}
-
-void PosixSemaphore::wait() {
-  int ret;
-
-  do {
-    ret = sem_wait(&_semaphore);
-  } while (ret != 0 && errno == EINTR);
-
-  assert_with_errno(ret == 0, "sem_wait failed");
-}
-
-bool PosixSemaphore::trywait() {
-  int ret;
-
-  do {
-    ret = sem_trywait(&_semaphore);
-  } while (ret != 0 && errno == EINTR);
-
-  assert_with_errno(ret == 0 || errno == EAGAIN, "trywait failed");
-
-  return ret == 0;
-}
-
-bool PosixSemaphore::timedwait(struct timespec ts) {
-  while (true) {
-    int result = sem_timedwait(&_semaphore, &ts);
-    if (result == 0) {
-      return true;
-    } else if (errno == EINTR) {
-      continue;
-    } else if (errno == ETIMEDOUT) {
-      return false;
-    } else {
-      assert_with_errno(false, "timedwait failed");
-      return false;
-    }
-  }
-}
-
-#endif // __APPLE__
-
 
 // Shared pthread_mutex/cond based PlatformEvent implementation.
 // Not currently usable by Solaris.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/hotspot/os/posix/semaphore_posix.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -0,0 +1,98 @@
+/*
+ * Copyright (c) 2018, 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.
+ *
+ */
+
+#include "precompiled/precompiled.hpp"
+#ifndef __APPLE__
+#include "runtime/os.hpp"
+// POSIX unamed semaphores are not supported on OS X.
+#include "semaphore_posix.hpp"
+#include <semaphore.h>
+
+#define check_with_errno(check_type, cond, msg)                             \
+  do {                                                                      \
+    int err = errno;                                                        \
+    check_type(cond, "%s; error='%s' (errno=%s)", msg, os::strerror(err),   \
+               os::errno_name(err));                                        \
+} while (false)
+
+#define assert_with_errno(cond, msg)    check_with_errno(assert, cond, msg)
+#define guarantee_with_errno(cond, msg) check_with_errno(guarantee, cond, msg)
+
+PosixSemaphore::PosixSemaphore(uint value) {
+  int ret = sem_init(&_semaphore, 0, value);
+
+  guarantee_with_errno(ret == 0, "Failed to initialize semaphore");
+}
+
+PosixSemaphore::~PosixSemaphore() {
+  sem_destroy(&_semaphore);
+}
+
+void PosixSemaphore::signal(uint count) {
+  for (uint i = 0; i < count; i++) {
+    int ret = sem_post(&_semaphore);
+
+    assert_with_errno(ret == 0, "sem_post failed");
+  }
+}
+
+void PosixSemaphore::wait() {
+  int ret;
+
+  do {
+    ret = sem_wait(&_semaphore);
+  } while (ret != 0 && errno == EINTR);
+
+  assert_with_errno(ret == 0, "sem_wait failed");
+}
+
+bool PosixSemaphore::trywait() {
+  int ret;
+
+  do {
+    ret = sem_trywait(&_semaphore);
+  } while (ret != 0 && errno == EINTR);
+
+  assert_with_errno(ret == 0 || errno == EAGAIN, "trywait failed");
+
+  return ret == 0;
+}
+
+bool PosixSemaphore::timedwait(struct timespec ts) {
+  while (true) {
+    int result = sem_timedwait(&_semaphore, &ts);
+    if (result == 0) {
+      return true;
+    } else if (errno == EINTR) {
+      continue;
+    } else if (errno == ETIMEDOUT) {
+      return false;
+    } else {
+      assert_with_errno(false, "timedwait failed");
+      return false;
+    }
+  }
+}
+#endif // __APPLE__
+
--- a/src/hotspot/os/posix/semaphore_posix.hpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/os/posix/semaphore_posix.hpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2018, 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
@@ -45,15 +45,7 @@
   void wait();
 
   bool trywait();
-  bool timedwait(unsigned int sec, int nsec) {
-    return timedwait(create_timespec(sec, nsec));
-  }
-
- private:
   bool timedwait(struct timespec ts);
-
-  // OS specific implementation to create a timespec suitable for semaphores.
-  struct timespec create_timespec(unsigned int set, int nsec);
 };
 
 typedef PosixSemaphore SemaphoreImpl;
--- a/src/hotspot/os/solaris/os_solaris.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/os/solaris/os_solaris.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, 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
@@ -2062,7 +2062,7 @@
   return CAST_FROM_FN_PTR(void*, UserHandler);
 }
 
-struct timespec PosixSemaphore::create_timespec(unsigned int sec, int nsec) {
+static struct timespec create_semaphore_timespec(unsigned int sec, int nsec) {
   struct timespec ts;
   unpackTime(&ts, false, (sec * NANOSECS_PER_SEC) + nsec);
 
@@ -2100,7 +2100,7 @@
 static jint *pending_signals = NULL;
 static int *preinstalled_sigs = NULL;
 static struct sigaction *chainedsigactions = NULL;
-static sema_t sig_sem;
+static Semaphore* sig_sem = NULL;
 typedef int (*version_getting_t)();
 version_getting_t os::Solaris::get_libjsig_version = NULL;
 
@@ -2115,6 +2115,7 @@
   Sigexit = Maxsignum+1;
   assert(Maxsignum >0, "Unable to obtain max signal number");
 
+  // Initialize signal structures
   // pending_signals has one int per signal
   // The additional signal is for SIGEXIT - exit signal to signal_thread
   pending_signals = (jint *)os::malloc(sizeof(jint) * (Sigexit+1), mtInternal);
@@ -2132,21 +2133,22 @@
 }
 
 void os::signal_init_pd() {
-  int ret;
-
-  ret = ::sema_init(&sig_sem, 0, NULL, NULL);
-  assert(ret == 0, "sema_init() failed");
-}
-
-void os::signal_notify(int signal_number) {
-  int ret;
-
-  Atomic::inc(&pending_signals[signal_number]);
-  ret = ::sema_post(&sig_sem);
-  assert(ret == 0, "sema_post() failed");
-}
-
-static int check_pending_signals(bool wait_for_signal) {
+  // Initialize signal semaphore
+  sig_sem = new Semaphore();
+}
+
+void os::signal_notify(int sig) {
+  if (sig_sem != NULL) {
+    Atomic::inc(&pending_signals[sig]);
+    sig_sem->signal();
+  } else {
+    // Signal thread is not created with ReduceSignalUsage and signal_init_pd
+    // initialization isn't called.
+    assert(ReduceSignalUsage, "signal semaphore should be created");
+  }
+}
+
+static int check_pending_signals() {
   int ret;
   while (true) {
     for (int i = 0; i < Sigexit + 1; i++) {
@@ -2155,19 +2157,13 @@
         return i;
       }
     }
-    if (!wait_for_signal) {
-      return -1;
-    }
     JavaThread *thread = JavaThread::current();
     ThreadBlockInVM tbivm(thread);
 
     bool threadIsSuspended;
     do {
       thread->set_suspend_equivalent();
-      // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self()
-      while ((ret = ::sema_wait(&sig_sem)) == EINTR)
-        ;
-      assert(ret == 0, "sema_wait() failed");
+      sig_sem->wait();
 
       // were we externally suspended while we were waiting?
       threadIsSuspended = thread->handle_special_suspend_equivalent_condition();
@@ -2176,8 +2172,7 @@
         // another thread suspended us. We don't want to continue running
         // while suspended because that would surprise the thread that
         // suspended us.
-        ret = ::sema_post(&sig_sem);
-        assert(ret == 0, "sema_post() failed");
+        sig_sem->signal();
 
         thread->java_suspend_self();
       }
@@ -2185,12 +2180,8 @@
   }
 }
 
-int os::signal_lookup() {
-  return check_pending_signals(false);
-}
-
 int os::signal_wait() {
-  return check_pending_signals(true);
+  return check_pending_signals();
 }
 
 ////////////////////////////////////////////////////////////////////////////////
@@ -3599,7 +3590,7 @@
 
   // managed to send the signal and switch to SUSPEND_REQUEST, now wait for SUSPENDED
   while (true) {
-    if (sr_semaphore.timedwait(0, 2000 * NANOSECS_PER_MILLISEC)) {
+    if (sr_semaphore.timedwait(create_semaphore_timespec(0, 2000 * NANOSECS_PER_MILLISEC))) {
       break;
     } else {
       // timeout
@@ -3633,7 +3624,7 @@
 
   while (true) {
     if (sr_notify(osthread) == 0) {
-      if (sr_semaphore.timedwait(0, 2 * NANOSECS_PER_MILLISEC)) {
+      if (sr_semaphore.timedwait(create_semaphore_timespec(0, 2 * NANOSECS_PER_MILLISEC))) {
         if (osthread->sr.is_running()) {
           return;
         }
--- a/src/hotspot/os/windows/os_windows.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/os/windows/os_windows.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, 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
@@ -62,7 +62,6 @@
 #include "runtime/threadCritical.hpp"
 #include "runtime/timer.hpp"
 #include "runtime/vm_version.hpp"
-#include "semaphore_windows.hpp"
 #include "services/attachListener.hpp"
 #include "services/memTracker.hpp"
 #include "services/runtimeService.hpp"
@@ -1845,36 +1844,6 @@
   return (int)error;
 }
 
-WindowsSemaphore::WindowsSemaphore(uint value) {
-  _semaphore = ::CreateSemaphore(NULL, value, LONG_MAX, NULL);
-
-  guarantee(_semaphore != NULL, "CreateSemaphore failed with error code: %lu", GetLastError());
-}
-
-WindowsSemaphore::~WindowsSemaphore() {
-  ::CloseHandle(_semaphore);
-}
-
-void WindowsSemaphore::signal(uint count) {
-  if (count > 0) {
-    BOOL ret = ::ReleaseSemaphore(_semaphore, count, NULL);
-
-    assert(ret != 0, "ReleaseSemaphore failed with error code: %lu", GetLastError());
-  }
-}
-
-void WindowsSemaphore::wait() {
-  DWORD ret = ::WaitForSingleObject(_semaphore, INFINITE);
-  assert(ret != WAIT_FAILED,   "WaitForSingleObject failed with error code: %lu", GetLastError());
-  assert(ret == WAIT_OBJECT_0, "WaitForSingleObject failed with return value: %lu", ret);
-}
-
-bool WindowsSemaphore::trywait() {
-  DWORD ret = ::WaitForSingleObject(_semaphore, 0);
-  assert(ret != WAIT_FAILED,   "WaitForSingleObject failed with error code: %lu", GetLastError());
-  return ret == WAIT_OBJECT_0;
-}
-
 // sun.misc.Signal
 // NOTE that this is a workaround for an apparent kernel bug where if
 // a signal handler for SIGBREAK is installed then that signal handler
@@ -1966,13 +1935,14 @@
 
 // a counter for each possible signal value, including signal_thread exit signal
 static volatile jint pending_signals[NSIG+1] = { 0 };
-static HANDLE sig_sem = NULL;
+static Semaphore* sig_sem = NULL;
 
 void os::signal_init_pd() {
   // Initialize signal structures
   memset((void*)pending_signals, 0, sizeof(pending_signals));
 
-  sig_sem = ::CreateSemaphore(NULL, 0, NSIG+1, NULL);
+  // Initialize signal semaphore
+  sig_sem = new Semaphore();
 
   // Programs embedding the VM do not want it to attempt to receive
   // events like CTRL_LOGOFF_EVENT, which are used to implement the
@@ -1994,17 +1964,18 @@
   }
 }
 
-void os::signal_notify(int signal_number) {
-  BOOL ret;
+void os::signal_notify(int sig) {
   if (sig_sem != NULL) {
-    Atomic::inc(&pending_signals[signal_number]);
-    ret = ::ReleaseSemaphore(sig_sem, 1, NULL);
-    assert(ret != 0, "ReleaseSemaphore() failed");
-  }
-}
-
-static int check_pending_signals(bool wait_for_signal) {
-  DWORD ret;
+    Atomic::inc(&pending_signals[sig]);
+    sig_sem->signal();
+  } else {
+    // Signal thread is not created with ReduceSignalUsage and signal_init_pd
+    // initialization isn't called.
+    assert(ReduceSignalUsage, "signal semaphore should be created");
+  }
+}
+
+static int check_pending_signals() {
   while (true) {
     for (int i = 0; i < NSIG + 1; i++) {
       jint n = pending_signals[i];
@@ -2012,10 +1983,6 @@
         return i;
       }
     }
-    if (!wait_for_signal) {
-      return -1;
-    }
-
     JavaThread *thread = JavaThread::current();
 
     ThreadBlockInVM tbivm(thread);
@@ -2024,8 +1991,7 @@
     do {
       thread->set_suspend_equivalent();
       // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self()
-      ret = ::WaitForSingleObject(sig_sem, INFINITE);
-      assert(ret == WAIT_OBJECT_0, "WaitForSingleObject() failed");
+      sig_sem->wait();
 
       // were we externally suspended while we were waiting?
       threadIsSuspended = thread->handle_special_suspend_equivalent_condition();
@@ -2034,8 +2000,7 @@
         // another thread suspended us. We don't want to continue running
         // while suspended because that would surprise the thread that
         // suspended us.
-        ret = ::ReleaseSemaphore(sig_sem, 1, NULL);
-        assert(ret != 0, "ReleaseSemaphore() failed");
+        sig_sem->signal();
 
         thread->java_suspend_self();
       }
@@ -2043,12 +2008,8 @@
   }
 }
 
-int os::signal_lookup() {
-  return check_pending_signals(false);
-}
-
 int os::signal_wait() {
-  return check_pending_signals(true);
+  return check_pending_signals();
 }
 
 // Implicit OS exception handling
@@ -4394,13 +4355,49 @@
 
 // Is a (classpath) directory empty?
 bool os::dir_is_empty(const char* path) {
-  WIN32_FIND_DATA fd;
-  HANDLE f = FindFirstFile(path, &fd);
-  if (f == INVALID_HANDLE_VALUE) {
-    return true;
-  }
-  FindClose(f);
-  return false;
+  char* search_path = (char*)os::malloc(strlen(path) + 3, mtInternal);
+  if (search_path == NULL) {
+    errno = ENOMEM;
+    return false;
+  }
+  strcpy(search_path, path);
+  // Append "*", or possibly "\\*", to path
+  if (path[1] == ':' &&
+    (path[2] == '\0' ||
+    (path[2] == '\\' && path[3] == '\0'))) {
+    // No '\\' needed for cases like "Z:" or "Z:\"
+    strcat(search_path, "*");
+  }
+  else {
+    strcat(search_path, "\\*");
+  }
+  errno_t err = ERROR_SUCCESS;
+  wchar_t* wpath = create_unc_path(search_path, err);
+  if (err != ERROR_SUCCESS) {
+    if (wpath != NULL) {
+      destroy_unc_path(wpath);
+    }
+    os::free(search_path);
+    errno = err;
+    return false;
+  }
+  WIN32_FIND_DATAW fd;
+  HANDLE f = ::FindFirstFileW(wpath, &fd);
+  destroy_unc_path(wpath);
+  bool is_empty = true;
+  if (f != INVALID_HANDLE_VALUE) {
+    while (is_empty && ::FindNextFileW(f, &fd)) {
+      // An empty directory contains only the current directory file
+      // and the previous directory file.
+      if ((wcscmp(fd.cFileName, L".") != 0) &&
+          (wcscmp(fd.cFileName, L"..") != 0)) {
+        is_empty = false;
+      }
+    }
+    FindClose(f);
+  }
+  os::free(search_path);
+  return is_empty;
 }
 
 // create binary file, rewriting existing file if required
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/hotspot/os/windows/semaphore_windows.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -0,0 +1,60 @@
+/*
+ * Copyright (c) 2018, 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.
+ *
+ */
+
+#include "precompiled.hpp"
+#include "semaphore_windows.hpp"
+#include "utilities/debug.hpp"
+
+#include <windows.h>
+#include <errno.h>
+
+WindowsSemaphore::WindowsSemaphore(uint value) {
+  _semaphore = ::CreateSemaphore(NULL, value, LONG_MAX, NULL);
+
+  guarantee(_semaphore != NULL, "CreateSemaphore failed with error code: %lu", GetLastError());
+}
+
+WindowsSemaphore::~WindowsSemaphore() {
+  ::CloseHandle(_semaphore);
+}
+
+void WindowsSemaphore::signal(uint count) {
+  if (count > 0) {
+    BOOL ret = ::ReleaseSemaphore(_semaphore, count, NULL);
+
+    assert(ret != 0, "ReleaseSemaphore failed with error code: %lu", GetLastError());
+  }
+}
+
+void WindowsSemaphore::wait() {
+  DWORD ret = ::WaitForSingleObject(_semaphore, INFINITE);
+  assert(ret != WAIT_FAILED,   "WaitForSingleObject failed with error code: %lu", GetLastError());
+  assert(ret == WAIT_OBJECT_0, "WaitForSingleObject failed with return value: %lu", ret);
+}
+
+bool WindowsSemaphore::trywait() {
+  DWORD ret = ::WaitForSingleObject(_semaphore, 0);
+  assert(ret != WAIT_FAILED,   "WaitForSingleObject failed with error code: %lu", GetLastError());
+  return ret == WAIT_OBJECT_0;
+}
--- a/src/hotspot/share/aot/aotCompiledMethod.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/aot/aotCompiledMethod.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -270,7 +270,7 @@
         CompiledIC *ic = CompiledIC_at(&iter);
         if (ic->is_icholder_call()) {
           CompiledICHolder* cichk = ic->cached_icholder();
-          f(cichk->holder_method());
+          f(cichk->holder_metadata());
           f(cichk->holder_klass());
         } else {
           // Get Klass* or NULL (if value is -1) from GOT cell of virtual call PLT stub.
--- a/src/hotspot/share/ci/ciInstanceKlass.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/ci/ciInstanceKlass.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -34,35 +34,12 @@
 #include "oops/oop.inline.hpp"
 #include "oops/fieldStreams.hpp"
 #include "runtime/fieldDescriptor.hpp"
-#if INCLUDE_ALL_GCS
-# include "gc/g1/g1SATBCardTableModRefBS.hpp"
-#endif
 
 // ciInstanceKlass
 //
 // This class represents a Klass* in the HotSpot virtual machine
 // whose Klass part in an InstanceKlass.
 
-// ------------------------------------------------------------------
-// ensure_metadata_alive
-//
-// Ensure that the metadata wrapped by the ciMetadata is kept alive by GC.
-// This is primarily useful for metadata which is considered as weak roots
-// by the GC but need to be strong roots if reachable from a current compilation.
-// InstanceKlass are created for both weak and strong metadata.  Ensuring this metadata
-// alive covers the cases where there are weak roots without performance cost.
-//
-static void ensure_metadata_alive(oop metadata_holder) {
-#if INCLUDE_ALL_GCS
-  if (!UseG1GC) {
-    return;
-  }
-  if (metadata_holder != NULL) {
-    G1SATBCardTableModRefBS::enqueue(metadata_holder);
-  }
-#endif
-}
-
 
 // ------------------------------------------------------------------
 // ciInstanceKlass::ciInstanceKlass
@@ -88,8 +65,12 @@
   _has_injected_fields = -1;
   _implementor = NULL; // we will fill these lazily
 
-  oop holder = ik->klass_holder();
-  ensure_metadata_alive(holder);
+  // Ensure that the metadata wrapped by the ciMetadata is kept alive by GC.
+  // This is primarily useful for metadata which is considered as weak roots
+  // by the GC but need to be strong roots if reachable from a current compilation.
+  // InstanceKlass are created for both weak and strong metadata.  Ensuring this metadata
+  // alive covers the cases where there are weak roots without performance cost.
+  oop holder = ik->klass_holder_phantom();
   if (ik->is_anonymous()) {
     // Though ciInstanceKlass records class loader oop, it's not enough to keep
     // VM anonymous classes alive (loader == NULL). Klass holder should be used instead.
--- a/src/hotspot/share/classfile/classLoaderData.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/classfile/classLoaderData.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -63,6 +63,7 @@
 #include "memory/metaspaceShared.hpp"
 #include "memory/oopFactory.hpp"
 #include "memory/resourceArea.hpp"
+#include "oops/access.inline.hpp"
 #include "oops/objArrayOop.inline.hpp"
 #include "oops/oop.inline.hpp"
 #include "runtime/atomic.hpp"
@@ -75,9 +76,6 @@
 #include "utilities/growableArray.hpp"
 #include "utilities/macros.hpp"
 #include "utilities/ostream.hpp"
-#if INCLUDE_ALL_GCS
-#include "gc/g1/g1SATBCardTableModRefBS.hpp"
-#endif // INCLUDE_ALL_GCS
 #if INCLUDE_TRACE
 #include "trace/tracing.hpp"
 #endif
@@ -759,18 +757,9 @@
   oop* ptr = h.ptr_raw();
   if (ptr != NULL) {
     assert(_handles.contains(ptr), "Got unexpected handle " PTR_FORMAT, p2i(ptr));
-#if INCLUDE_ALL_GCS
-    // This barrier is used by G1 to remember the old oop values, so
-    // that we don't forget any objects that were live at the snapshot at
-    // the beginning.
-    if (UseG1GC) {
-      oop obj = *ptr;
-      if (obj != NULL) {
-        G1SATBCardTableModRefBS::enqueue(obj);
-      }
-    }
-#endif
-    *ptr = NULL;
+    // This root is not walked in safepoints, and hence requires an appropriate
+    // decorator that e.g. maintains the SATB invariant in SATB collectors.
+    RootAccess<IN_CONCURRENT_ROOT>::oop_store(ptr, oop(NULL));
   }
 }
 
--- a/src/hotspot/share/classfile/classLoaderData.hpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/classfile/classLoaderData.hpp	Fri Jan 19 09:32:10 2018 -0800
@@ -217,6 +217,7 @@
   friend class ClassLoaderDataGraphKlassIteratorAtomic;
   friend class ClassLoaderDataGraphKlassIteratorStatic;
   friend class ClassLoaderDataGraphMetaspaceIterator;
+  friend class InstanceKlass;
   friend class MetaDataFactory;
   friend class Method;
 
--- a/src/hotspot/share/classfile/javaClasses.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/classfile/javaClasses.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, 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,8 @@
 #include "code/dependencyContext.hpp"
 #include "code/pcDesc.hpp"
 #include "interpreter/interpreter.hpp"
+#include "logging/log.hpp"
+#include "logging/logStream.hpp"
 #include "memory/oopFactory.hpp"
 #include "memory/resourceArea.hpp"
 #include "memory/universe.inline.hpp"
@@ -104,52 +106,59 @@
 }
 
 
-static bool find_field(InstanceKlass* ik,
-                       Symbol* name_symbol, Symbol* signature_symbol,
-                       fieldDescriptor* fd,
-                       bool is_static = false, bool allow_super = false) {
-  if (allow_super || is_static) {
-    return ik->find_field(name_symbol, signature_symbol, is_static, fd) != NULL;
-  } else {
-    return ik->find_local_field(name_symbol, signature_symbol, fd);
+// Helpful routine for computing field offsets at run time rather than hardcoding them
+// Finds local fields only, including static fields.  Static field offsets are from the
+// beginning of the mirror.
+static void compute_offset(int &dest_offset,
+                           InstanceKlass* ik, Symbol* name_symbol, Symbol* signature_symbol,
+                           bool is_static = false) {
+  fieldDescriptor fd;
+  if (ik == NULL) {
+    ResourceMark rm;
+    log_error(class)("Mismatch JDK version for field: %s type: %s", name_symbol->as_C_string(), signature_symbol->as_C_string());
+    vm_exit_during_initialization("Invalid layout of preloaded class");
   }
-}
-
-// Helpful routine for computing field offsets at run time rather than hardcoding them
-static void
-compute_offset(int &dest_offset,
-               Klass* klass, Symbol* name_symbol, Symbol* signature_symbol,
-               bool is_static = false, bool allow_super = false) {
-  fieldDescriptor fd;
-  InstanceKlass* ik = InstanceKlass::cast(klass);
-  if (!find_field(ik, name_symbol, signature_symbol, &fd, is_static, allow_super)) {
+
+  if (!ik->find_local_field(name_symbol, signature_symbol, &fd) || fd.is_static() != is_static) {
     ResourceMark rm;
-    tty->print_cr("Invalid layout of %s at %s", ik->external_name(), name_symbol->as_C_string());
+    log_error(class)("Invalid layout of %s field: %s type: %s", ik->external_name(),
+                     name_symbol->as_C_string(), signature_symbol->as_C_string());
 #ifndef PRODUCT
-    ik->print();
-    tty->print_cr("all fields:");
-    for (AllFieldStream fs(ik); !fs.done(); fs.next()) {
-      tty->print_cr("  name: %s, sig: %s, flags: %08x", fs.name()->as_C_string(), fs.signature()->as_C_string(), fs.access_flags().as_int());
-    }
+    // Prints all fields and offsets
+    Log(class) lt;
+    LogStream ls(lt.error());
+    ik->print_on(&ls);
 #endif //PRODUCT
     vm_exit_during_initialization("Invalid layout of preloaded class: use -Xlog:class+load=info to see the origin of the problem class");
   }
   dest_offset = fd.offset();
 }
 
+// Overloading to pass name as a string.
+static void compute_offset(int& dest_offset, InstanceKlass* ik,
+                           const char* name_string, Symbol* signature_symbol,
+                           bool is_static = false) {
+  TempNewSymbol name = SymbolTable::probe(name_string, (int)strlen(name_string));
+  if (name == NULL) {
+    ResourceMark rm;
+    log_error(class)("Name %s should be in the SymbolTable since its class is loaded", name_string);
+    vm_exit_during_initialization("Invalid layout of preloaded class", ik->external_name());
+  }
+  compute_offset(dest_offset, ik, name, signature_symbol, is_static);
+}
+
 // Same as above but for "optional" offsets that might not be present in certain JDK versions
+// Old versions should be cleaned out since Hotspot only supports the current JDK, and this
+// function should be removed.
 static void
 compute_optional_offset(int& dest_offset,
-                        Klass* klass, Symbol* name_symbol, Symbol* signature_symbol,
-                        bool allow_super = false) {
+                        InstanceKlass* ik, Symbol* name_symbol, Symbol* signature_symbol) {
   fieldDescriptor fd;
-  InstanceKlass* ik = InstanceKlass::cast(klass);
-  if (find_field(ik, name_symbol, signature_symbol, &fd, allow_super)) {
+  if (ik->find_local_field(name_symbol, signature_symbol, &fd)) {
     dest_offset = fd.offset();
   }
 }
 
-
 int java_lang_String::value_offset  = 0;
 int java_lang_String::hash_offset   = 0;
 int java_lang_String::coder_offset  = 0;
@@ -163,10 +172,10 @@
 void java_lang_String::compute_offsets() {
   assert(!initialized, "offsets should be initialized only once");
 
-  Klass* k = SystemDictionary::String_klass();
+  InstanceKlass* k = SystemDictionary::String_klass();
   compute_offset(value_offset,           k, vmSymbols::value_name(),  vmSymbols::byte_array_signature());
-  compute_offset(hash_offset,            k, vmSymbols::hash_name(),   vmSymbols::int_signature());
-  compute_offset(coder_offset,           k, vmSymbols::coder_name(),  vmSymbols::byte_signature());
+  compute_offset(hash_offset,            k, "hash",   vmSymbols::int_signature());
+  compute_offset(coder_offset,           k, "coder",  vmSymbols::byte_signature());
 
   initialized = true;
 }
@@ -619,12 +628,12 @@
 bool java_lang_String::equals(oop java_string, jchar* chars, int len) {
   assert(java_string->klass() == SystemDictionary::String_klass(),
          "must be java_string");
-  typeArrayOop value  = java_lang_String::value(java_string);
-  int          length = java_lang_String::length(java_string);
+  typeArrayOop value = java_lang_String::value_no_keepalive(java_string);
+  int length = java_lang_String::length(java_string);
   if (length != len) {
     return false;
   }
-  bool      is_latin1 = java_lang_String::is_latin1(java_string);
+  bool is_latin1 = java_lang_String::is_latin1(java_string);
   if (!is_latin1) {
     for (int i = 0; i < len; i++) {
       if (value->char_at(i) != chars[i]) {
@@ -646,12 +655,12 @@
          "must be java String");
   assert(str2->klass() == SystemDictionary::String_klass(),
          "must be java String");
-  typeArrayOop value1  = java_lang_String::value(str1);
-  int          length1 = java_lang_String::length(str1);
-  bool       is_latin1 = java_lang_String::is_latin1(str1);
-  typeArrayOop value2  = java_lang_String::value(str2);
-  int          length2 = java_lang_String::length(str2);
-  bool       is_latin2 = java_lang_String::is_latin1(str2);
+  typeArrayOop value1    = java_lang_String::value_no_keepalive(str1);
+  int          length1   = java_lang_String::length(value1);
+  bool         is_latin1 = java_lang_String::is_latin1(str1);
+  typeArrayOop value2    = java_lang_String::value_no_keepalive(str2);
+  int          length2   = java_lang_String::length(value2);
+  bool         is_latin2 = java_lang_String::is_latin1(str2);
 
   if ((length1 != length2) || (is_latin1 != is_latin2)) {
     // Strings of different size or with different
@@ -659,7 +668,7 @@
     return false;
   }
   int blength1 = value1->length();
-  for (int i = 0; i < value1->length(); i++) {
+  for (int i = 0; i < blength1; i++) {
     if (value1->byte_at(i) != value2->byte_at(i)) {
       return false;
     }
@@ -669,7 +678,7 @@
 
 void java_lang_String::print(oop java_string, outputStream* st) {
   assert(java_string->klass() == SystemDictionary::String_klass(), "must be java_string");
-  typeArrayOop value  = java_lang_String::value(java_string);
+  typeArrayOop value  = java_lang_String::value_no_keepalive(java_string);
 
   if (value == NULL) {
     // This can happen if, e.g., printing a String
@@ -1161,25 +1170,11 @@
   assert(!offsets_computed, "offsets should be initialized only once");
   offsets_computed = true;
 
-  Klass* k = SystemDictionary::Class_klass();
-  // The classRedefinedCount field is only present starting in 1.5,
-  // so don't go fatal.
-  compute_optional_offset(classRedefinedCount_offset,
-                          k, vmSymbols::classRedefinedCount_name(), vmSymbols::int_signature());
-
-  // Needs to be optional because the old build runs Queens during bootstrapping
-  // and jdk8-9 doesn't have coordinated pushes yet.
-  compute_optional_offset(_class_loader_offset,
-                 k, vmSymbols::classLoader_name(),
-                 vmSymbols::classloader_signature());
-
-  compute_offset(_component_mirror_offset,
-                 k, vmSymbols::componentType_name(),
-                 vmSymbols::class_signature());
-
-  compute_offset(_module_offset,
-                 k, vmSymbols::module_name(),
-                 vmSymbols::module_signature());
+  InstanceKlass* k = SystemDictionary::Class_klass();
+  compute_offset(classRedefinedCount_offset, k, "classRedefinedCount", vmSymbols::int_signature());
+  compute_offset(_class_loader_offset,       k, "classLoader", vmSymbols::classloader_signature());
+  compute_offset(_component_mirror_offset,   k, "componentType", vmSymbols::class_signature());
+  compute_offset(_module_offset,             k, "module", vmSymbols::module_signature());
 
   // Init lock is a C union with component_mirror.  Only instanceKlass mirrors have
   // init_lock and only ArrayKlass mirrors have component_mirror.  Since both are oops
@@ -1234,24 +1229,22 @@
 void java_lang_Thread::compute_offsets() {
   assert(_group_offset == 0, "offsets should be initialized only once");
 
-  Klass* k = SystemDictionary::Thread_klass();
+  InstanceKlass* k = SystemDictionary::Thread_klass();
   compute_offset(_name_offset,      k, vmSymbols::name_name(),      vmSymbols::string_signature());
   compute_offset(_group_offset,     k, vmSymbols::group_name(),     vmSymbols::threadgroup_signature());
-  compute_offset(_contextClassLoader_offset, k, vmSymbols::contextClassLoader_name(), vmSymbols::classloader_signature());
-  compute_offset(_inheritedAccessControlContext_offset, k, vmSymbols::inheritedAccessControlContext_name(), vmSymbols::accesscontrolcontext_signature());
+  compute_offset(_contextClassLoader_offset, k, vmSymbols::contextClassLoader_name(),
+                 vmSymbols::classloader_signature());
+  compute_offset(_inheritedAccessControlContext_offset, k, vmSymbols::inheritedAccessControlContext_name(),
+                 vmSymbols::accesscontrolcontext_signature());
   compute_offset(_priority_offset,  k, vmSymbols::priority_name(),  vmSymbols::int_signature());
   compute_offset(_daemon_offset,    k, vmSymbols::daemon_name(),    vmSymbols::bool_signature());
-  compute_offset(_eetop_offset,     k, vmSymbols::eetop_name(),     vmSymbols::long_signature());
-  compute_offset(_stillborn_offset, k, vmSymbols::stillborn_name(), vmSymbols::bool_signature());
-  // The stackSize field is only present starting in 1.4, so don't go fatal.
-  compute_optional_offset(_stackSize_offset, k, vmSymbols::stackSize_name(), vmSymbols::long_signature());
-  // The tid and thread_status fields are only present starting in 1.5, so don't go fatal.
-  compute_optional_offset(_tid_offset, k, vmSymbols::thread_id_name(), vmSymbols::long_signature());
-  compute_optional_offset(_thread_status_offset, k, vmSymbols::thread_status_name(), vmSymbols::int_signature());
-  // The parkBlocker field is only present starting in 1.6, so don't go fatal.
-  compute_optional_offset(_park_blocker_offset, k, vmSymbols::park_blocker_name(), vmSymbols::object_signature());
-  compute_optional_offset(_park_event_offset, k, vmSymbols::park_event_name(),
- vmSymbols::long_signature());
+  compute_offset(_eetop_offset,     k, "eetop", vmSymbols::long_signature());
+  compute_offset(_stillborn_offset, k, "stillborn", vmSymbols::bool_signature());
+  compute_offset(_stackSize_offset, k, "stackSize", vmSymbols::long_signature());
+  compute_offset(_tid_offset,       k, "tid", vmSymbols::long_signature());
+  compute_offset(_thread_status_offset, k, "threadStatus", vmSymbols::int_signature());
+  compute_offset(_park_blocker_offset,  k, "parkBlocker", vmSymbols::object_signature());
+  compute_offset(_park_event_offset,    k, "nativeParkEventPointer", vmSymbols::long_signature());
 }
 
 
@@ -1486,7 +1479,7 @@
 void java_lang_ThreadGroup::compute_offsets() {
   assert(_parent_offset == 0, "offsets should be initialized only once");
 
-  Klass* k = SystemDictionary::ThreadGroup_klass();
+  InstanceKlass* k = SystemDictionary::ThreadGroup_klass();
 
   compute_offset(_parent_offset,      k, vmSymbols::parent_name(),      vmSymbols::threadgroup_signature());
   compute_offset(_name_offset,        k, vmSymbols::name_name(),        vmSymbols::string_signature());
@@ -1501,8 +1494,13 @@
 
 
 void java_lang_Throwable::compute_offsets() {
-  Klass* k = SystemDictionary::Throwable_klass();
-  compute_offset(depth_offset, k, vmSymbols::depth_name(), vmSymbols::int_signature());
+  InstanceKlass* k = SystemDictionary::Throwable_klass();
+  compute_offset(backtrace_offset,     k, "backtrace", vmSymbols::object_signature());
+  compute_offset(detailMessage_offset, k, "detailMessage", vmSymbols::string_signature());
+  compute_offset(stackTrace_offset,    k, "stackTrace",    vmSymbols::java_lang_StackTraceElement_array());
+  compute_offset(depth_offset,         k, "depth", vmSymbols::int_signature());
+  compute_offset(static_unassigned_stacktrace_offset, k, "UNASSIGNED_STACK", vmSymbols::java_lang_StackTraceElement_array(),
+                 /*is_static*/true);
 }
 
 oop java_lang_Throwable::unassigned_stacktrace() {
@@ -2270,23 +2268,23 @@
 }
 
 void java_lang_StackFrameInfo::compute_offsets() {
-  Klass* k = SystemDictionary::StackFrameInfo_klass();
-  compute_offset(_memberName_offset,     k, vmSymbols::memberName_name(),  vmSymbols::object_signature());
-  compute_offset(_bci_offset,            k, vmSymbols::bci_name(),         vmSymbols::short_signature());
+  InstanceKlass* k = SystemDictionary::StackFrameInfo_klass();
+  compute_offset(_memberName_offset,     k, "memberName",  vmSymbols::object_signature());
+  compute_offset(_bci_offset,            k, "bci",         vmSymbols::short_signature());
   STACKFRAMEINFO_INJECTED_FIELDS(INJECTED_FIELD_COMPUTE_OFFSET);
 }
 
 void java_lang_LiveStackFrameInfo::compute_offsets() {
-  Klass* k = SystemDictionary::LiveStackFrameInfo_klass();
-  compute_offset(_monitors_offset,   k, vmSymbols::monitors_name(),    vmSymbols::object_array_signature());
-  compute_offset(_locals_offset,     k, vmSymbols::locals_name(),      vmSymbols::object_array_signature());
-  compute_offset(_operands_offset,   k, vmSymbols::operands_name(),    vmSymbols::object_array_signature());
-  compute_offset(_mode_offset,       k, vmSymbols::mode_name(),        vmSymbols::int_signature());
+  InstanceKlass* k = SystemDictionary::LiveStackFrameInfo_klass();
+  compute_offset(_monitors_offset,   k, "monitors",    vmSymbols::object_array_signature());
+  compute_offset(_locals_offset,     k, "locals",      vmSymbols::object_array_signature());
+  compute_offset(_operands_offset,   k, "operands",    vmSymbols::object_array_signature());
+  compute_offset(_mode_offset,       k, "mode",        vmSymbols::int_signature());
 }
 
 void java_lang_reflect_AccessibleObject::compute_offsets() {
-  Klass* k = SystemDictionary::reflect_AccessibleObject_klass();
-  compute_offset(override_offset, k, vmSymbols::override_name(), vmSymbols::bool_signature());
+  InstanceKlass* k = SystemDictionary::reflect_AccessibleObject_klass();
+  compute_offset(override_offset, k, "override", vmSymbols::bool_signature());
 }
 
 jboolean java_lang_reflect_AccessibleObject::override(oop reflect) {
@@ -2300,7 +2298,7 @@
 }
 
 void java_lang_reflect_Method::compute_offsets() {
-  Klass* k = SystemDictionary::reflect_Method_klass();
+  InstanceKlass* k = SystemDictionary::reflect_Method_klass();
   compute_offset(clazz_offset,          k, vmSymbols::clazz_name(),          vmSymbols::class_signature());
   compute_offset(name_offset,           k, vmSymbols::name_name(),           vmSymbols::string_signature());
   compute_offset(returnType_offset,     k, vmSymbols::returnType_name(),     vmSymbols::class_signature());
@@ -2481,7 +2479,7 @@
 }
 
 void java_lang_reflect_Constructor::compute_offsets() {
-  Klass* k = SystemDictionary::reflect_Constructor_klass();
+  InstanceKlass* k = SystemDictionary::reflect_Constructor_klass();
   compute_offset(clazz_offset,          k, vmSymbols::clazz_name(),          vmSymbols::class_signature());
   compute_offset(parameterTypes_offset, k, vmSymbols::parameterTypes_name(), vmSymbols::class_array_signature());
   compute_offset(exceptionTypes_offset, k, vmSymbols::exceptionTypes_name(), vmSymbols::class_array_signature());
@@ -2623,7 +2621,7 @@
 }
 
 void java_lang_reflect_Field::compute_offsets() {
-  Klass* k = SystemDictionary::reflect_Field_klass();
+  InstanceKlass* k = SystemDictionary::reflect_Field_klass();
   compute_offset(clazz_offset,     k, vmSymbols::clazz_name(),     vmSymbols::class_signature());
   compute_offset(name_offset,      k, vmSymbols::name_name(),      vmSymbols::string_signature());
   compute_offset(type_offset,      k, vmSymbols::type_name(),      vmSymbols::class_signature());
@@ -2747,22 +2745,17 @@
 }
 
 void reflect_ConstantPool::compute_offsets() {
-  Klass* k = SystemDictionary::reflect_ConstantPool_klass();
-  // This null test can be removed post beta
-  if (k != NULL) {
-    // The field is called ConstantPool* in the sun.reflect.ConstantPool class.
-    compute_offset(_oop_offset, k, vmSymbols::ConstantPool_name(), vmSymbols::object_signature());
-  }
+  InstanceKlass* k = SystemDictionary::reflect_ConstantPool_klass();
+  // The field is called ConstantPool* in the sun.reflect.ConstantPool class.
+  compute_offset(_oop_offset, k, "constantPoolOop", vmSymbols::object_signature());
 }
 
 void java_lang_reflect_Parameter::compute_offsets() {
-  Klass* k = SystemDictionary::reflect_Parameter_klass();
-  if(NULL != k) {
-    compute_offset(name_offset,        k, vmSymbols::name_name(),        vmSymbols::string_signature());
-    compute_offset(modifiers_offset,   k, vmSymbols::modifiers_name(),   vmSymbols::int_signature());
-    compute_offset(index_offset,       k, vmSymbols::index_name(),       vmSymbols::int_signature());
-    compute_offset(executable_offset,  k, vmSymbols::executable_name(),  vmSymbols::executable_signature());
-  }
+  InstanceKlass* k = SystemDictionary::reflect_Parameter_klass();
+  compute_offset(name_offset,        k, vmSymbols::name_name(),        vmSymbols::string_signature());
+  compute_offset(modifiers_offset,   k, vmSymbols::modifiers_name(),   vmSymbols::int_signature());
+  compute_offset(index_offset,       k, vmSymbols::index_name(),       vmSymbols::int_signature());
+  compute_offset(executable_offset,  k, vmSymbols::executable_name(),  vmSymbols::executable_signature());
 }
 
 Handle java_lang_reflect_Parameter::create(TRAPS) {
@@ -2836,12 +2829,10 @@
 }
 
 void java_lang_Module::compute_offsets() {
-  Klass* k = SystemDictionary::Module_klass();
-  if(NULL != k) {
-    compute_offset(loader_offset,  k, vmSymbols::loader_name(),  vmSymbols::classloader_signature());
-    compute_offset(name_offset,    k, vmSymbols::name_name(),    vmSymbols::string_signature());
-    MODULE_INJECTED_FIELDS(INJECTED_FIELD_COMPUTE_OFFSET);
-  }
+  InstanceKlass* k = SystemDictionary::Module_klass();
+  compute_offset(loader_offset,  k, vmSymbols::loader_name(),  vmSymbols::classloader_signature());
+  compute_offset(name_offset,    k, vmSymbols::name_name(),    vmSymbols::string_signature());
+  MODULE_INJECTED_FIELDS(INJECTED_FIELD_COMPUTE_OFFSET);
 }
 
 
@@ -2921,12 +2912,8 @@
 }
 
 void reflect_UnsafeStaticFieldAccessorImpl::compute_offsets() {
-  Klass* k = SystemDictionary::reflect_UnsafeStaticFieldAccessorImpl_klass();
-  // This null test can be removed post beta
-  if (k != NULL) {
-    compute_offset(_base_offset, k,
-                   vmSymbols::base_name(), vmSymbols::object_signature());
-  }
+  InstanceKlass* k = SystemDictionary::reflect_UnsafeStaticFieldAccessorImpl_klass();
+  compute_offset(_base_offset, k, "base", vmSymbols::object_signature());
 }
 
 oop java_lang_boxing_object::initialize_and_allocate(BasicType type, TRAPS) {
@@ -3084,6 +3071,13 @@
 }
 
 // Support for java_lang_ref_SoftReference
+//
+
+void java_lang_ref_SoftReference::compute_offsets() {
+  InstanceKlass* k = SystemDictionary::SoftReference_klass();
+  compute_offset(timestamp_offset,    k, "timestamp", vmSymbols::long_signature());
+  compute_offset(static_clock_offset, k, "clock",     vmSymbols::long_signature(), true);
+}
 
 jlong java_lang_ref_SoftReference::timestamp(oop ref) {
   return ref->long_field(timestamp_offset);
@@ -3113,10 +3107,8 @@
 }
 
 void java_lang_invoke_DirectMethodHandle::compute_offsets() {
-  Klass* k = SystemDictionary::DirectMethodHandle_klass();
-  if (k != NULL) {
-    compute_offset(_member_offset, k, vmSymbols::member_name(), vmSymbols::java_lang_invoke_MemberName_signature());
-  }
+  InstanceKlass* k = SystemDictionary::DirectMethodHandle_klass();
+  compute_offset(_member_offset, k, "member", vmSymbols::java_lang_invoke_MemberName_signature());
 }
 
 // Support for java_lang_invoke_MethodHandle
@@ -3137,16 +3129,13 @@
 int java_lang_invoke_LambdaForm::_vmentry_offset;
 
 void java_lang_invoke_MethodHandle::compute_offsets() {
-  Klass* k = SystemDictionary::MethodHandle_klass();
-  if (k != NULL) {
-    compute_offset(_type_offset, k, vmSymbols::type_name(), vmSymbols::java_lang_invoke_MethodType_signature());
-    compute_offset(_form_offset, k, vmSymbols::form_name(), vmSymbols::java_lang_invoke_LambdaForm_signature());
-  }
+  InstanceKlass* k = SystemDictionary::MethodHandle_klass();
+  compute_offset(_type_offset, k, vmSymbols::type_name(), vmSymbols::java_lang_invoke_MethodType_signature());
+  compute_offset(_form_offset, k, "form", vmSymbols::java_lang_invoke_LambdaForm_signature());
 }
 
 void java_lang_invoke_MemberName::compute_offsets() {
-  Klass* k = SystemDictionary::MemberName_klass();
-  assert (k != NULL, "jdk mismatch");
+  InstanceKlass* k = SystemDictionary::MemberName_klass();
   compute_offset(_clazz_offset,   k, vmSymbols::clazz_name(),   vmSymbols::class_signature());
   compute_offset(_name_offset,    k, vmSymbols::name_name(),    vmSymbols::string_signature());
   compute_offset(_type_offset,    k, vmSymbols::type_name(),    vmSymbols::object_signature());
@@ -3156,15 +3145,15 @@
 }
 
 void java_lang_invoke_ResolvedMethodName::compute_offsets() {
-  Klass* k = SystemDictionary::ResolvedMethodName_klass();
+  InstanceKlass* k = SystemDictionary::ResolvedMethodName_klass();
   assert(k != NULL, "jdk mismatch");
   RESOLVEDMETHOD_INJECTED_FIELDS(INJECTED_FIELD_COMPUTE_OFFSET);
 }
 
 void java_lang_invoke_LambdaForm::compute_offsets() {
-  Klass* k = SystemDictionary::LambdaForm_klass();
+  InstanceKlass* k = SystemDictionary::LambdaForm_klass();
   assert (k != NULL, "jdk mismatch");
-  compute_offset(_vmentry_offset, k, vmSymbols::vmentry_name(), vmSymbols::java_lang_invoke_MemberName_signature());
+  compute_offset(_vmentry_offset, k, "vmentry", vmSymbols::java_lang_invoke_MemberName_signature());
 }
 
 bool java_lang_invoke_LambdaForm::is_instance(oop obj) {
@@ -3305,11 +3294,9 @@
 int java_lang_invoke_MethodType::_ptypes_offset;
 
 void java_lang_invoke_MethodType::compute_offsets() {
-  Klass* k = SystemDictionary::MethodType_klass();
-  if (k != NULL) {
-    compute_offset(_rtype_offset,  k, vmSymbols::rtype_name(),  vmSymbols::class_signature());
-    compute_offset(_ptypes_offset, k, vmSymbols::ptypes_name(), vmSymbols::class_array_signature());
-  }
+  InstanceKlass* k = SystemDictionary::MethodType_klass();
+  compute_offset(_rtype_offset,  k, "rtype",  vmSymbols::class_signature());
+  compute_offset(_ptypes_offset, k, "ptypes", vmSymbols::class_array_signature());
 }
 
 void java_lang_invoke_MethodType::print_signature(oop mt, outputStream* st) {
@@ -3392,12 +3379,10 @@
 int java_lang_invoke_CallSite::_context_offset;
 
 void java_lang_invoke_CallSite::compute_offsets() {
-  Klass* k = SystemDictionary::CallSite_klass();
-  if (k != NULL) {
-    compute_offset(_target_offset, k, vmSymbols::target_name(), vmSymbols::java_lang_invoke_MethodHandle_signature());
-    compute_offset(_context_offset, k, vmSymbols::context_name(),
-                   vmSymbols::java_lang_invoke_MethodHandleNatives_CallSiteContext_signature());
-  }
+  InstanceKlass* k = SystemDictionary::CallSite_klass();
+  compute_offset(_target_offset,  k, "target", vmSymbols::java_lang_invoke_MethodHandle_signature());
+  compute_offset(_context_offset, k, "context",
+                 vmSymbols::java_lang_invoke_MethodHandleNatives_CallSiteContext_signature());
 }
 
 oop java_lang_invoke_CallSite::context(oop call_site) {
@@ -3412,10 +3397,8 @@
 int java_lang_invoke_MethodHandleNatives_CallSiteContext::_vmdependencies_offset;
 
 void java_lang_invoke_MethodHandleNatives_CallSiteContext::compute_offsets() {
-  Klass* k = SystemDictionary::Context_klass();
-  if (k != NULL) {
-    CALLSITECONTEXT_INJECTED_FIELDS(INJECTED_FIELD_COMPUTE_OFFSET);
-  }
+  InstanceKlass* k = SystemDictionary::Context_klass();
+  CALLSITECONTEXT_INJECTED_FIELDS(INJECTED_FIELD_COMPUTE_OFFSET);
 }
 
 DependencyContext java_lang_invoke_MethodHandleNatives_CallSiteContext::vmdependencies(oop call_site) {
@@ -3434,28 +3417,12 @@
 
 void java_security_AccessControlContext::compute_offsets() {
   assert(_isPrivileged_offset == 0, "offsets should be initialized only once");
-  fieldDescriptor fd;
-  InstanceKlass* ik = SystemDictionary::AccessControlContext_klass();
-
-  if (!ik->find_local_field(vmSymbols::context_name(), vmSymbols::protectiondomain_signature(), &fd)) {
-    fatal("Invalid layout of java.security.AccessControlContext");
-  }
-  _context_offset = fd.offset();
-
-  if (!ik->find_local_field(vmSymbols::privilegedContext_name(), vmSymbols::accesscontrolcontext_signature(), &fd)) {
-    fatal("Invalid layout of java.security.AccessControlContext");
-  }
-  _privilegedContext_offset = fd.offset();
-
-  if (!ik->find_local_field(vmSymbols::isPrivileged_name(), vmSymbols::bool_signature(), &fd)) {
-    fatal("Invalid layout of java.security.AccessControlContext");
-  }
-  _isPrivileged_offset = fd.offset();
-
-  // The offset may not be present for bootstrapping with older JDK.
-  if (ik->find_local_field(vmSymbols::isAuthorized_name(), vmSymbols::bool_signature(), &fd)) {
-    _isAuthorized_offset = fd.offset();
-  }
+  InstanceKlass* k = SystemDictionary::AccessControlContext_klass();
+
+  compute_offset(_context_offset,           k, "context",      vmSymbols::protectiondomain_signature());
+  compute_offset(_privilegedContext_offset, k, "privilegedContext", vmSymbols::accesscontrolcontext_signature());
+  compute_offset(_isPrivileged_offset,      k, "isPrivileged", vmSymbols::bool_signature());
+  compute_offset(_isAuthorized_offset,      k, "isAuthorized", vmSymbols::bool_signature());
 }
 
 
@@ -3504,16 +3471,17 @@
   assert(!offsets_computed, "offsets should be initialized only once");
   offsets_computed = true;
 
-  // The field indicating parallelCapable (parallelLockMap) is only present starting in 7,
-  Klass* k1 = SystemDictionary::ClassLoader_klass();
-  compute_optional_offset(parallelCapable_offset,
-    k1, vmSymbols::parallelCapable_name(), vmSymbols::concurrenthashmap_signature());
+  InstanceKlass* k1 = SystemDictionary::ClassLoader_klass();
+  compute_offset(parallelCapable_offset,
+    k1, "parallelLockMap", vmSymbols::concurrenthashmap_signature());
 
   compute_offset(name_offset,
     k1, vmSymbols::name_name(), vmSymbols::string_signature());
 
   compute_offset(unnamedModule_offset,
-    k1, vmSymbols::unnamedModule_name(), vmSymbols::module_signature());
+    k1, "unnamedModule", vmSymbols::module_signature());
+
+  compute_offset(parent_offset, k1, "parent", vmSymbols::classloader_signature());
 
   CLASSLOADER_INJECTED_FIELDS(INJECTED_FIELD_COMPUTE_OFFSET);
 }
@@ -3600,19 +3568,18 @@
 }
 
 // Support for java_lang_System
-int java_lang_System::in_offset_in_bytes() {
-  return (InstanceMirrorKlass::offset_of_static_fields() + static_in_offset);
-}
-
-
-int java_lang_System::out_offset_in_bytes() {
-  return (InstanceMirrorKlass::offset_of_static_fields() + static_out_offset);
-}
-
-
-int java_lang_System::err_offset_in_bytes() {
-  return (InstanceMirrorKlass::offset_of_static_fields() + static_err_offset);
-}
+//
+void java_lang_System::compute_offsets() {
+  InstanceKlass* k = SystemDictionary::System_klass();
+  compute_offset(static_in_offset,  k, "in",  vmSymbols::input_stream_signature(), true);
+  compute_offset(static_out_offset, k, "out", vmSymbols::print_stream_signature(), true);
+  compute_offset(static_err_offset, k, "err", vmSymbols::print_stream_signature(), true);
+  compute_offset(static_security_offset, k, "security", vmSymbols::security_manager_signature(), true);
+}
+
+int java_lang_System::in_offset_in_bytes() { return static_in_offset; }
+int java_lang_System::out_offset_in_bytes() { return static_out_offset; }
+int java_lang_System::err_offset_in_bytes() { return static_err_offset; }
 
 
 bool java_lang_System::has_security_manager() {
@@ -3682,7 +3649,6 @@
 int java_lang_ref_Reference::queue_offset;
 int java_lang_ref_Reference::next_offset;
 int java_lang_ref_Reference::discovered_offset;
-int java_lang_ref_Reference::number_of_fake_oop_fields;
 int java_lang_ref_SoftReference::timestamp_offset;
 int java_lang_ref_SoftReference::static_clock_offset;
 int java_lang_ClassLoader::parent_offset;
@@ -3717,6 +3683,17 @@
 
 
 // Support for java_lang_StackTraceElement
+void java_lang_StackTraceElement::compute_offsets() {
+  InstanceKlass* k = SystemDictionary::StackTraceElement_klass();
+  compute_offset(declaringClassObject_offset,  k, "declaringClassObject", vmSymbols::class_signature());
+  compute_offset(classLoaderName_offset, k, "classLoaderName", vmSymbols::string_signature());
+  compute_offset(moduleName_offset,      k, "moduleName",      vmSymbols::string_signature());
+  compute_offset(moduleVersion_offset,   k, "moduleVersion",   vmSymbols::string_signature());
+  compute_offset(declaringClass_offset,  k, "declaringClass",  vmSymbols::string_signature());
+  compute_offset(methodName_offset,      k, "methodName",      vmSymbols::string_signature());
+  compute_offset(fileName_offset,        k, "fileName",        vmSymbols::string_signature());
+  compute_offset(lineNumber_offset,      k, "lineNumber",      vmSymbols::int_signature());
+}
 
 void java_lang_StackTraceElement::set_fileName(oop element, oop value) {
   element->obj_field_put(fileName_offset, value);
@@ -3776,6 +3753,16 @@
 
 // Support for java Assertions - java_lang_AssertionStatusDirectives.
 
+void java_lang_AssertionStatusDirectives::compute_offsets() {
+  InstanceKlass* k = SystemDictionary::AssertionStatusDirectives_klass();
+  compute_offset(classes_offset,        k, "classes",        vmSymbols::string_array_signature());
+  compute_offset(classEnabled_offset,   k, "classEnabled",   vmSymbols::bool_array_signature());
+  compute_offset(packages_offset,       k, "packages",       vmSymbols::string_array_signature());
+  compute_offset(packageEnabled_offset, k, "packageEnabled", vmSymbols::bool_array_signature());
+  compute_offset(deflt_offset,          k, "deflt",          vmSymbols::bool_signature());
+}
+
+
 void java_lang_AssertionStatusDirectives::set_classes(oop o, oop val) {
   o->obj_field_put(classes_offset, val);
 }
@@ -3804,18 +3791,18 @@
 
 
 void java_nio_Buffer::compute_offsets() {
-  Klass* k = SystemDictionary::nio_Buffer_klass();
+  InstanceKlass* k = SystemDictionary::nio_Buffer_klass();
   assert(k != NULL, "must be loaded in 1.4+");
-  compute_offset(_limit_offset, k, vmSymbols::limit_name(), vmSymbols::int_signature());
+  compute_offset(_limit_offset, k, "limit", vmSymbols::int_signature());
 }
 
 void java_util_concurrent_locks_AbstractOwnableSynchronizer::initialize(TRAPS) {
   if (_owner_offset != 0) return;
 
   SystemDictionary::load_abstract_ownable_synchronizer_klass(CHECK);
-  Klass* k = SystemDictionary::abstract_ownable_synchronizer_klass();
+  InstanceKlass* k = SystemDictionary::abstract_ownable_synchronizer_klass();
   compute_offset(_owner_offset, k,
-                 vmSymbols::exclusive_owner_thread_name(), vmSymbols::thread_signature());
+                 "exclusiveOwnerThread", vmSymbols::thread_signature());
 }
 
 oop java_util_concurrent_locks_AbstractOwnableSynchronizer::get_owner_threadObj(oop obj) {
@@ -3823,71 +3810,37 @@
   return obj->obj_field(_owner_offset);
 }
 
+static int member_offset(int hardcoded_offset) {
+  return (hardcoded_offset * heapOopSize) + instanceOopDesc::base_offset_in_bytes();
+}
+
 // Compute hard-coded offsets
 // Invoked before SystemDictionary::initialize, so pre-loaded classes
 // are not available to determine the offset_of_static_fields.
 void JavaClasses::compute_hard_coded_offsets() {
-  const int x = heapOopSize;
-  const int header = instanceOopDesc::base_offset_in_bytes();
-
-  // Throwable Class
-  java_lang_Throwable::backtrace_offset  = java_lang_Throwable::hc_backtrace_offset  * x + header;
-  java_lang_Throwable::detailMessage_offset = java_lang_Throwable::hc_detailMessage_offset * x + header;
-  java_lang_Throwable::stackTrace_offset = java_lang_Throwable::hc_stackTrace_offset * x + header;
-  java_lang_Throwable::static_unassigned_stacktrace_offset = java_lang_Throwable::hc_static_unassigned_stacktrace_offset *  x;
 
   // java_lang_boxing_object
-  java_lang_boxing_object::value_offset = java_lang_boxing_object::hc_value_offset + header;
-  java_lang_boxing_object::long_value_offset = align_up((java_lang_boxing_object::hc_value_offset + header), BytesPerLong);
-
-  // java_lang_ref_Reference:
-  java_lang_ref_Reference::referent_offset = java_lang_ref_Reference::hc_referent_offset * x + header;
-  java_lang_ref_Reference::queue_offset = java_lang_ref_Reference::hc_queue_offset * x + header;
-  java_lang_ref_Reference::next_offset  = java_lang_ref_Reference::hc_next_offset * x + header;
-  java_lang_ref_Reference::discovered_offset  = java_lang_ref_Reference::hc_discovered_offset * x + header;
-  // Artificial fields for java_lang_ref_Reference
-  // The first field is for the discovered field added in 1.4
-  java_lang_ref_Reference::number_of_fake_oop_fields = 1;
-
-  // java_lang_ref_SoftReference Class
-  java_lang_ref_SoftReference::timestamp_offset = align_up((java_lang_ref_SoftReference::hc_timestamp_offset * x + header), BytesPerLong);
-  // Don't multiply static fields because they are always in wordSize units
-  java_lang_ref_SoftReference::static_clock_offset = java_lang_ref_SoftReference::hc_static_clock_offset * x;
-
-  // java_lang_ClassLoader
-  java_lang_ClassLoader::parent_offset = java_lang_ClassLoader::hc_parent_offset * x + header;
-
-  // java_lang_System
-  java_lang_System::static_in_offset  = java_lang_System::hc_static_in_offset  * x;
-  java_lang_System::static_out_offset = java_lang_System::hc_static_out_offset * x;
-  java_lang_System::static_err_offset = java_lang_System::hc_static_err_offset * x;
-  java_lang_System::static_security_offset = java_lang_System::hc_static_security_offset * x;
-
-  // java_lang_StackTraceElement
-  java_lang_StackTraceElement::declaringClassObject_offset = java_lang_StackTraceElement::hc_declaringClassObject_offset * x + header;
-  java_lang_StackTraceElement::classLoaderName_offset = java_lang_StackTraceElement::hc_classLoaderName_offset * x + header;
-  java_lang_StackTraceElement::moduleName_offset = java_lang_StackTraceElement::hc_moduleName_offset * x + header;
-  java_lang_StackTraceElement::moduleVersion_offset = java_lang_StackTraceElement::hc_moduleVersion_offset * x + header;
-  java_lang_StackTraceElement::declaringClass_offset = java_lang_StackTraceElement::hc_declaringClass_offset  * x + header;
-  java_lang_StackTraceElement::methodName_offset = java_lang_StackTraceElement::hc_methodName_offset * x + header;
-  java_lang_StackTraceElement::fileName_offset   = java_lang_StackTraceElement::hc_fileName_offset   * x + header;
-  java_lang_StackTraceElement::lineNumber_offset = java_lang_StackTraceElement::hc_lineNumber_offset * x + header;
-  java_lang_AssertionStatusDirectives::classes_offset = java_lang_AssertionStatusDirectives::hc_classes_offset * x + header;
-  java_lang_AssertionStatusDirectives::classEnabled_offset = java_lang_AssertionStatusDirectives::hc_classEnabled_offset * x + header;
-  java_lang_AssertionStatusDirectives::packages_offset = java_lang_AssertionStatusDirectives::hc_packages_offset * x + header;
-  java_lang_AssertionStatusDirectives::packageEnabled_offset = java_lang_AssertionStatusDirectives::hc_packageEnabled_offset * x + header;
-  java_lang_AssertionStatusDirectives::deflt_offset = java_lang_AssertionStatusDirectives::hc_deflt_offset * x + header;
-
+  java_lang_boxing_object::value_offset      = member_offset(java_lang_boxing_object::hc_value_offset);
+  java_lang_boxing_object::long_value_offset = align_up(member_offset(java_lang_boxing_object::hc_value_offset), BytesPerLong);
+
+  // java_lang_ref_Reference
+  java_lang_ref_Reference::referent_offset    = member_offset(java_lang_ref_Reference::hc_referent_offset);
+  java_lang_ref_Reference::queue_offset       = member_offset(java_lang_ref_Reference::hc_queue_offset);
+  java_lang_ref_Reference::next_offset        = member_offset(java_lang_ref_Reference::hc_next_offset);
+  java_lang_ref_Reference::discovered_offset  = member_offset(java_lang_ref_Reference::hc_discovered_offset);
 }
 
 
 // Compute non-hard-coded field offsets of all the classes in this file
 void JavaClasses::compute_offsets() {
   // java_lang_Class::compute_offsets was called earlier in bootstrap
+  java_lang_System::compute_offsets();
   java_lang_ClassLoader::compute_offsets();
   java_lang_Throwable::compute_offsets();
   java_lang_Thread::compute_offsets();
   java_lang_ThreadGroup::compute_offsets();
+  java_lang_AssertionStatusDirectives::compute_offsets();
+  java_lang_ref_SoftReference::compute_offsets();
   java_lang_invoke_MethodHandle::compute_offsets();
   java_lang_invoke_DirectMethodHandle::compute_offsets();
   java_lang_invoke_MemberName::compute_offsets();
@@ -3910,6 +3863,7 @@
   reflect_UnsafeStaticFieldAccessorImpl::compute_offsets();
   java_lang_reflect_Parameter::compute_offsets();
   java_lang_Module::compute_offsets();
+  java_lang_StackTraceElement::compute_offsets();
   java_lang_StackFrameInfo::compute_offsets();
   java_lang_LiveStackFrameInfo::compute_offsets();
 
@@ -3947,62 +3901,6 @@
   }
 }
 
-
-bool JavaClasses::check_static_offset(const char *klass_name, int hardcoded_offset, const char *field_name, const char* field_sig) {
-  EXCEPTION_MARK;
-  fieldDescriptor fd;
-  TempNewSymbol klass_sym = SymbolTable::new_symbol(klass_name, CATCH);
-  Klass* k = SystemDictionary::resolve_or_fail(klass_sym, true, CATCH);
-  InstanceKlass* ik = InstanceKlass::cast(k);
-  TempNewSymbol f_name = SymbolTable::new_symbol(field_name, CATCH);
-  TempNewSymbol f_sig  = SymbolTable::new_symbol(field_sig, CATCH);
-  if (!ik->find_local_field(f_name, f_sig, &fd)) {
-    tty->print_cr("Static field %s.%s not found", klass_name, field_name);
-    return false;
-  }
-  if (!fd.is_static()) {
-    tty->print_cr("Static field %s.%s appears to be nonstatic", klass_name, field_name);
-    return false;
-  }
-  if (fd.offset() == hardcoded_offset + InstanceMirrorKlass::offset_of_static_fields()) {
-    return true;
-  } else {
-    tty->print_cr("Offset of static field %s.%s is hardcoded as %d but should really be %d.", klass_name, field_name, hardcoded_offset, fd.offset() - InstanceMirrorKlass::offset_of_static_fields());
-    return false;
-  }
-}
-
-
-bool JavaClasses::check_constant(const char *klass_name, int hardcoded_constant, const char *field_name, const char* field_sig) {
-  EXCEPTION_MARK;
-  fieldDescriptor fd;
-  TempNewSymbol klass_sym = SymbolTable::new_symbol(klass_name, CATCH);
-  Klass* k = SystemDictionary::resolve_or_fail(klass_sym, true, CATCH);
-  InstanceKlass* ik = InstanceKlass::cast(k);
-  TempNewSymbol f_name = SymbolTable::new_symbol(field_name, CATCH);
-  TempNewSymbol f_sig  = SymbolTable::new_symbol(field_sig, CATCH);
-  if (!ik->find_local_field(f_name, f_sig, &fd)) {
-    tty->print_cr("Static field %s.%s not found", klass_name, field_name);
-    return false;
-  }
-  if (!fd.is_static() || !fd.has_initial_value()) {
-    tty->print_cr("Static field %s.%s appears to be non-constant", klass_name, field_name);
-    return false;
-  }
-  if (!fd.initial_value_tag().is_int()) {
-    tty->print_cr("Static field %s.%s is not an int", klass_name, field_name);
-    return false;
-  }
-  jint field_value = fd.int_initial_value();
-  if (field_value == hardcoded_constant) {
-    return true;
-  } else {
-    tty->print_cr("Constant value of static field %s.%s is hardcoded as %d but should really be %d.", klass_name, field_name, hardcoded_constant, field_value);
-    return false;
-  }
-}
-
-
 // Check the hard-coded field offsets of all the classes in this file
 
 void JavaClasses::check_offsets() {
@@ -4014,31 +3912,6 @@
 #define CHECK_LONG_OFFSET(klass_name, cpp_klass_name, field_name, field_sig) \
   valid &= check_offset(klass_name, cpp_klass_name :: long_ ## field_name ## _offset, #field_name, field_sig)
 
-#define CHECK_STATIC_OFFSET(klass_name, cpp_klass_name, field_name, field_sig) \
-  valid &= check_static_offset(klass_name, cpp_klass_name :: static_ ## field_name ## _offset, #field_name, field_sig)
-
-#define CHECK_CONSTANT(klass_name, cpp_klass_name, field_name, field_sig) \
-  valid &= check_constant(klass_name, cpp_klass_name :: field_name, #field_name, field_sig)
-
-  // java.lang.String
-
-  CHECK_OFFSET("java/lang/String", java_lang_String, value, "[B");
-  CHECK_OFFSET("java/lang/String", java_lang_String, hash, "I");
-  CHECK_OFFSET("java/lang/String", java_lang_String, coder, "B");
-
-  // java.lang.Class
-
-  // Fake fields
-  // CHECK_OFFSET("java/lang/Class", java_lang_Class, klass); // %%% this needs to be checked
-  // CHECK_OFFSET("java/lang/Class", java_lang_Class, array_klass); // %%% this needs to be checked
-
-  // java.lang.Throwable
-
-  CHECK_OFFSET("java/lang/Throwable", java_lang_Throwable, backtrace, "Ljava/lang/Object;");
-  CHECK_OFFSET("java/lang/Throwable", java_lang_Throwable, detailMessage, "Ljava/lang/String;");
-  CHECK_OFFSET("java/lang/Throwable", java_lang_Throwable, stackTrace, "[Ljava/lang/StackTraceElement;");
-  CHECK_OFFSET("java/lang/Throwable", java_lang_Throwable, depth, "I");
-
   // Boxed primitive objects (java_lang_boxing_object)
 
   CHECK_OFFSET("java/lang/Boolean",   java_lang_boxing_object, value, "Z");
@@ -4050,28 +3923,6 @@
   CHECK_OFFSET("java/lang/Integer",   java_lang_boxing_object, value, "I");
   CHECK_LONG_OFFSET("java/lang/Long", java_lang_boxing_object, value, "J");
 
-  // java.lang.ClassLoader
-
-  CHECK_OFFSET("java/lang/ClassLoader", java_lang_ClassLoader, parent,        "Ljava/lang/ClassLoader;");
-
-  // java.lang.System
-
-  CHECK_STATIC_OFFSET("java/lang/System", java_lang_System,  in, "Ljava/io/InputStream;");
-  CHECK_STATIC_OFFSET("java/lang/System", java_lang_System, out, "Ljava/io/PrintStream;");
-  CHECK_STATIC_OFFSET("java/lang/System", java_lang_System, err, "Ljava/io/PrintStream;");
-  CHECK_STATIC_OFFSET("java/lang/System", java_lang_System, security, "Ljava/lang/SecurityManager;");
-
-  // java.lang.StackTraceElement
-
-  CHECK_OFFSET("java/lang/StackTraceElement", java_lang_StackTraceElement, declaringClassObject, "Ljava/lang/Class;");
-  CHECK_OFFSET("java/lang/StackTraceElement", java_lang_StackTraceElement, classLoaderName, "Ljava/lang/String;");
-  CHECK_OFFSET("java/lang/StackTraceElement", java_lang_StackTraceElement, moduleName,      "Ljava/lang/String;");
-  CHECK_OFFSET("java/lang/StackTraceElement", java_lang_StackTraceElement, moduleVersion,   "Ljava/lang/String;");
-  CHECK_OFFSET("java/lang/StackTraceElement", java_lang_StackTraceElement, declaringClass,  "Ljava/lang/String;");
-  CHECK_OFFSET("java/lang/StackTraceElement", java_lang_StackTraceElement, methodName,      "Ljava/lang/String;");
-  CHECK_OFFSET("java/lang/StackTraceElement", java_lang_StackTraceElement, fileName,        "Ljava/lang/String;");
-  CHECK_OFFSET("java/lang/StackTraceElement", java_lang_StackTraceElement, lineNumber,      "I");
-
   // java.lang.ref.Reference
 
   CHECK_OFFSET("java/lang/ref/Reference", java_lang_ref_Reference, referent, "Ljava/lang/Object;");
@@ -4080,28 +3931,6 @@
   // Fake field
   //CHECK_OFFSET("java/lang/ref/Reference", java_lang_ref_Reference, discovered, "Ljava/lang/ref/Reference;");
 
-  // java.lang.ref.SoftReference
-
-  CHECK_OFFSET("java/lang/ref/SoftReference", java_lang_ref_SoftReference, timestamp, "J");
-  CHECK_STATIC_OFFSET("java/lang/ref/SoftReference", java_lang_ref_SoftReference, clock, "J");
-
-  // java.lang.AssertionStatusDirectives
-  //
-  // The CheckAssertionStatusDirectives boolean can be removed from here and
-  // globals.hpp after the AssertionStatusDirectives class has been integrated
-  // into merlin "for some time."  Without it, the vm will fail with early
-  // merlin builds.
-
-  if (CheckAssertionStatusDirectives) {
-    const char* nm = "java/lang/AssertionStatusDirectives";
-    const char* sig = "[Ljava/lang/String;";
-    CHECK_OFFSET(nm, java_lang_AssertionStatusDirectives, classes, sig);
-    CHECK_OFFSET(nm, java_lang_AssertionStatusDirectives, classEnabled, "[Z");
-    CHECK_OFFSET(nm, java_lang_AssertionStatusDirectives, packages, sig);
-    CHECK_OFFSET(nm, java_lang_AssertionStatusDirectives, packageEnabled, "[Z");
-    CHECK_OFFSET(nm, java_lang_AssertionStatusDirectives, deflt, "Z");
-  }
-
   if (!valid) vm_exit_during_initialization("Hard-coded field offset verification failed");
 }
 
--- a/src/hotspot/share/classfile/javaClasses.hpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/classfile/javaClasses.hpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, 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
@@ -102,6 +102,7 @@
 
   // Accessors
   static inline typeArrayOop value(oop java_string);
+  static inline typeArrayOop value_no_keepalive(oop java_string);
   static inline unsigned int hash(oop java_string);
   static inline bool is_latin1(oop java_string);
   static inline int length(oop java_string);
@@ -444,9 +445,6 @@
     hc_cause_offset         =  2,  // New since 1.4
     hc_stackTrace_offset    =  3   // New since 1.4
   };
-  enum {
-      hc_static_unassigned_stacktrace_offset = 0  // New since 1.7
-  };
   // Trace constants
   enum {
     trace_methods_offset = 0,
@@ -878,7 +876,6 @@
   static int queue_offset;
   static int next_offset;
   static int discovered_offset;
-  static int number_of_fake_oop_fields;
 
   // Accessors
   static inline oop referent(oop ref);
@@ -902,14 +899,6 @@
 
 class java_lang_ref_SoftReference: public java_lang_ref_Reference {
  public:
-  enum {
-   // The timestamp is a long field and may need to be adjusted for alignment.
-   hc_timestamp_offset  = hc_discovered_offset + 1
-  };
-  enum {
-   hc_static_clock_offset = 0
-  };
-
   static int timestamp_offset;
   static int static_clock_offset;
 
@@ -919,6 +908,8 @@
   // Accessors for statics
   static jlong clock();
   static void set_clock(jlong value);
+
+  static void compute_offsets();
 };
 
 // Interface to java.lang.invoke.MethodHandle objects
@@ -1228,10 +1219,6 @@
 
 class java_lang_ClassLoader : AllStatic {
  private:
-  // The fake offsets are added by the class loader when java.lang.Class is loaded
-  enum {
-   hc_parent_offset = 0
-  };
   static int _loader_data_offset;
   static bool offsets_computed;
   static int parent_offset;
@@ -1279,13 +1266,6 @@
 
 class java_lang_System : AllStatic {
  private:
-  enum {
-   hc_static_in_offset  = 0,
-   hc_static_out_offset = 1,
-   hc_static_err_offset = 2,
-   hc_static_security_offset = 3
-  };
-
   static int  static_in_offset;
   static int static_out_offset;
   static int static_err_offset;
@@ -1298,6 +1278,8 @@
 
   static bool has_security_manager();
 
+  static void compute_offsets();
+
   // Debugging
   friend class JavaClasses;
 };
@@ -1307,17 +1289,6 @@
 
 class java_lang_StackTraceElement: AllStatic {
  private:
-  enum {
-    hc_declaringClassObject_offset    = 0,
-    hc_classLoaderName_offset      = 1,
-    hc_moduleName_offset           = 2,
-    hc_moduleVersion_offset        = 3,
-    hc_declaringClass_offset       = 4,
-    hc_methodName_offset           = 5,
-    hc_fileName_offset             = 6,
-    hc_lineNumber_offset           = 7
-  };
-
   static int declaringClassObject_offset;
   static int classLoaderName_offset;
   static int moduleName_offset;
@@ -1344,6 +1315,8 @@
   static void fill_in(Handle element, InstanceKlass* holder, const methodHandle& method,
                       int version, int bci, Symbol* name, TRAPS);
 
+  static void compute_offsets();
+
   // Debugging
   friend class JavaClasses;
 };
@@ -1416,14 +1389,6 @@
 
 class java_lang_AssertionStatusDirectives: AllStatic {
  private:
-  enum {
-    hc_classes_offset,
-    hc_classEnabled_offset,
-    hc_packages_offset,
-    hc_packageEnabled_offset,
-    hc_deflt_offset
-  };
-
   static int classes_offset;
   static int classEnabled_offset;
   static int packages_offset;
@@ -1437,6 +1402,9 @@
   static void set_packages(oop obj, oop val);
   static void set_packageEnabled(oop obj, oop val);
   static void set_deflt(oop obj, bool val);
+
+  static void compute_offsets();
+
   // Debugging
   friend class JavaClasses;
 };
@@ -1508,9 +1476,6 @@
   static InjectedField _injected_fields[];
 
   static bool check_offset(const char *klass_name, int offset, const char *field_name, const char* field_sig) PRODUCT_RETURN0;
-  static bool check_static_offset(const char *klass_name, int hardcoded_offset, const char *field_name, const char* field_sig) PRODUCT_RETURN0;
-  static bool check_constant(const char *klass_name, int constant, const char *field_name, const char* field_sig) PRODUCT_RETURN0;
-
  public:
   enum InjectedFieldID {
     ALL_INJECTED_FIELDS(DECLARE_INJECTED_FIELD_ENUM)
--- a/src/hotspot/share/classfile/javaClasses.inline.hpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/classfile/javaClasses.inline.hpp	Fri Jan 19 09:32:10 2018 -0800
@@ -26,6 +26,7 @@
 #define SHARE_VM_CLASSFILE_JAVACLASSES_INLINE_HPP
 
 #include "classfile/javaClasses.hpp"
+#include "oops/access.inline.hpp"
 #include "oops/oop.inline.hpp"
 #include "oops/oopsHierarchy.hpp"
 
@@ -53,6 +54,11 @@
   assert(is_instance(java_string), "must be java_string");
   return (typeArrayOop) java_string->obj_field(value_offset);
 }
+typeArrayOop java_lang_String::value_no_keepalive(oop java_string) {
+  assert(initialized && (value_offset > 0), "Must be initialized");
+  assert(is_instance(java_string), "must be java_string");
+  return (typeArrayOop) java_string->obj_field_access<AS_NO_KEEPALIVE>(value_offset);
+}
 unsigned int java_lang_String::hash(oop java_string) {
   assert(initialized && (hash_offset > 0), "Must be initialized");
   assert(is_instance(java_string), "must be java_string");
@@ -68,11 +74,11 @@
 int java_lang_String::length(oop java_string) {
   assert(initialized, "Must be initialized");
   assert(is_instance(java_string), "must be java_string");
-  typeArrayOop value_array = ((typeArrayOop)java_string->obj_field(value_offset));
-  if (value_array == NULL) {
+  typeArrayOop value = java_lang_String::value_no_keepalive(java_string);
+  if (value == NULL) {
     return 0;
   }
-  int arr_length = value_array->length();
+  int arr_length = value->length();
   if (!is_latin1(java_string)) {
     assert((arr_length & 1) == 0, "should be even for UTF16 string");
     arr_length >>= 1; // convert number of bytes to number of elements
--- a/src/hotspot/share/classfile/stringTable.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/classfile/stringTable.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -35,6 +35,7 @@
 #include "memory/filemap.hpp"
 #include "memory/metaspaceShared.hpp"
 #include "memory/resourceArea.hpp"
+#include "oops/access.inline.hpp"
 #include "oops/oop.inline.hpp"
 #include "runtime/atomic.hpp"
 #include "runtime/mutexLocker.hpp"
@@ -43,7 +44,6 @@
 #include "utilities/macros.hpp"
 #if INCLUDE_ALL_GCS
 #include "gc/g1/g1CollectedHeap.hpp"
-#include "gc/g1/g1SATBCardTableModRefBS.hpp"
 #include "gc/g1/g1StringDedup.hpp"
 #endif
 
@@ -124,6 +124,22 @@
   }
 }
 
+oop StringTable::string_object(HashtableEntry<oop, mtSymbol>* entry) {
+  return RootAccess<ON_PHANTOM_OOP_REF>::oop_load(entry->literal_addr());
+}
+
+oop StringTable::string_object_no_keepalive(HashtableEntry<oop, mtSymbol>* entry) {
+  // The AS_NO_KEEPALIVE peeks at the oop without keeping it alive.
+  // This is *very dangerous* in general but is okay in this specific
+  // case. The subsequent oop_load keeps the oop alive if it it matched
+  // the jchar* string.
+  return RootAccess<ON_PHANTOM_OOP_REF | AS_NO_KEEPALIVE>::oop_load(entry->literal_addr());
+}
+
+void StringTable::set_string_object(HashtableEntry<oop, mtSymbol>* entry, oop string) {
+  RootAccess<ON_PHANTOM_OOP_REF>::oop_store(entry->literal_addr(), string);
+}
+
 oop StringTable::lookup_shared(jchar* name, int len, unsigned int hash) {
   assert(hash == java_lang_String::hash_code(name, len),
          "hash must be computed using java_lang_String::hash_code");
@@ -131,13 +147,16 @@
 }
 
 oop StringTable::lookup_in_main_table(int index, jchar* name,
-                                int len, unsigned int hash) {
+                                      int len, unsigned int hash) {
   int count = 0;
   for (HashtableEntry<oop, mtSymbol>* l = bucket(index); l != NULL; l = l->next()) {
     count++;
     if (l->hash() == hash) {
-      if (java_lang_String::equals(l->literal(), name, len)) {
-        return l->literal();
+      if (java_lang_String::equals(string_object_no_keepalive(l), name, len)) {
+        // We must perform a new load with string_object() that keeps the string
+        // alive as we must expose the oop as strongly reachable when exiting
+        // this context, in case the oop gets published.
+        return string_object(l);
       }
     }
   }
@@ -192,18 +211,6 @@
   return lookup(chars, length);
 }
 
-// Tell the GC that this string was looked up in the StringTable.
-static void ensure_string_alive(oop string) {
-  // A lookup in the StringTable could return an object that was previously
-  // considered dead. The SATB part of G1 needs to get notified about this
-  // potential resurrection, otherwise the marking might not find the object.
-#if INCLUDE_ALL_GCS
-  if (UseG1GC && string != NULL) {
-    G1SATBCardTableModRefBS::enqueue(string);
-  }
-#endif
-}
-
 oop StringTable::lookup(jchar* name, int len) {
   // shared table always uses java_lang_String::hash_code
   unsigned int hash = java_lang_String::hash_code(name, len);
@@ -217,8 +224,6 @@
   int index = the_table()->hash_to_index(hash);
   string = the_table()->lookup_in_main_table(index, name, len, hash);
 
-  ensure_string_alive(string);
-
   return string;
 }
 
@@ -238,9 +243,6 @@
 
   // Found
   if (found_string != NULL) {
-    if (found_string != string_or_null()) {
-      ensure_string_alive(found_string);
-    }
     return found_string;
   }
 
@@ -276,10 +278,6 @@
                                   hashValue, CHECK_NULL);
   }
 
-  if (added_or_found != string()) {
-    ensure_string_alive(added_or_found);
-  }
-
   return added_or_found;
 }
 
@@ -388,9 +386,9 @@
     while (entry != NULL) {
       assert(!entry->is_shared(), "CDS not used for the StringTable");
 
-      if (is_alive->do_object_b(entry->literal())) {
+      if (is_alive->do_object_b(string_object_no_keepalive(entry))) {
         if (f != NULL) {
-          f->do_oop((oop*)entry->literal_addr());
+          f->do_oop(entry->literal_addr());
         }
         p = entry->next_addr();
       } else {
@@ -429,7 +427,7 @@
   for (int i = 0; i < the_table()->table_size(); ++i) {
     HashtableEntry<oop, mtSymbol>* p = the_table()->bucket(i);
     for ( ; p != NULL; p = p->next()) {
-      oop s = p->literal();
+      oop s = string_object_no_keepalive(p);
       guarantee(s != NULL, "interned string is NULL");
       unsigned int h = hash_string(s);
       guarantee(p->hash() == h, "broken hash in string table entry");
@@ -448,10 +446,10 @@
     for (int i = 0; i < the_table()->table_size(); ++i) {
       HashtableEntry<oop, mtSymbol>* p = the_table()->bucket(i);
       for ( ; p != NULL; p = p->next()) {
-        oop s = p->literal();
-        typeArrayOop value  = java_lang_String::value(s);
-        int          length = java_lang_String::length(s);
-        bool      is_latin1 = java_lang_String::is_latin1(s);
+        oop s = string_object_no_keepalive(p);
+        typeArrayOop value     = java_lang_String::value_no_keepalive(s);
+        int          length    = java_lang_String::length(s);
+        bool         is_latin1 = java_lang_String::is_latin1(s);
 
         if (length <= 0) {
           st->print("%d: ", length);
@@ -484,8 +482,8 @@
                                       HashtableEntry<oop, mtSymbol>* e_ptr2) {
   // These entries are sanity checked by verify_and_compare_entries()
   // before this function is called.
-  oop str1 = e_ptr1->literal();
-  oop str2 = e_ptr2->literal();
+  oop str1 = string_object_no_keepalive(e_ptr1);
+  oop str2 = string_object_no_keepalive(e_ptr2);
 
   if (str1 == str2) {
     tty->print_cr("ERROR: identical oop values (0x" PTR_FORMAT ") "
@@ -505,12 +503,12 @@
 }
 
 StringTable::VerifyRetTypes StringTable::verify_entry(int bkt, int e_cnt,
-                                      HashtableEntry<oop, mtSymbol>* e_ptr,
-                                      StringTable::VerifyMesgModes mesg_mode) {
+                                                      HashtableEntry<oop, mtSymbol>* e_ptr,
+                                                      StringTable::VerifyMesgModes mesg_mode) {
 
   VerifyRetTypes ret = _verify_pass;  // be optimistic
 
-  oop str = e_ptr->literal();
+  oop str = string_object_no_keepalive(e_ptr);
   if (str == NULL) {
     if (mesg_mode == _verify_with_mesgs) {
       tty->print_cr("ERROR: NULL oop value in entry @ bucket[%d][%d]", bkt,
@@ -684,7 +682,7 @@
   assert(DumpSharedSpaces, "this function is only used with -Xshare:dump");
 
   oop new_s = NULL;
-  typeArrayOop v = java_lang_String::value(s);
+  typeArrayOop v = java_lang_String::value_no_keepalive(s);
   typeArrayOop new_v = (typeArrayOop)MetaspaceShared::archive_heap_object(v, THREAD);
   if (new_v == NULL) {
     return NULL;
@@ -708,7 +706,7 @@
   for (int i = 0; i < the_table()->table_size(); ++i) {
     HashtableEntry<oop, mtSymbol>* bucket = the_table()->bucket(i);
     for ( ; bucket != NULL; bucket = bucket->next()) {
-      oop s = bucket->literal();
+      oop s = string_object_no_keepalive(bucket);
       unsigned int hash = java_lang_String::hash_code(s);
       if (hash == 0) {
         continue;
@@ -721,7 +719,7 @@
       }
 
       // set the archived string in bucket
-      bucket->set_literal(new_s);
+      set_string_object(bucket, new_s);
 
       // add to the compact table
       writer->add(hash, new_s);
@@ -763,4 +761,3 @@
   _shared_table.oops_do(f);
 }
 #endif //INCLUDE_CDS_JAVA_HEAP
-
--- a/src/hotspot/share/classfile/stringTable.hpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/classfile/stringTable.hpp	Fri Jan 19 09:32:10 2018 -0800
@@ -76,6 +76,13 @@
   static unsigned int hash_string(oop string);
   static unsigned int alt_hash_string(const jchar* s, int len);
 
+  // Accessors for the string roots in the hashtable entries.
+  // Use string_object_no_keepalive() only when the value is not returned
+  // outside of a scope where a thread transition is possible.
+  static oop string_object(HashtableEntry<oop, mtSymbol>* entry);
+  static oop string_object_no_keepalive(HashtableEntry<oop, mtSymbol>* entry);
+  static void set_string_object(HashtableEntry<oop, mtSymbol>* entry, oop string);
+
   StringTable() : RehashableHashtable<oop, mtSymbol>((int)StringTableSize,
                               sizeof (HashtableEntry<oop, mtSymbol>)) {}
 
--- a/src/hotspot/share/classfile/systemDictionary.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/classfile/systemDictionary.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -2775,7 +2775,17 @@
   java_lang_invoke_MemberName::set_name (mname(), name_str());
   java_lang_invoke_MemberName::set_type (mname(), signature_str());
   java_lang_invoke_MemberName::set_flags(mname(), MethodHandles::ref_kind_to_flags(ref_kind));
-  MethodHandles::resolve_MemberName(mname, caller, CHECK_(empty));
+
+  if (ref_kind == JVM_REF_invokeVirtual &&
+      callee->name() == vmSymbols::java_lang_invoke_MethodHandle() &&
+      (name == vmSymbols::invoke_name() || name == vmSymbols::invokeExact_name())) {
+    // Skip resolution for j.l.i.MethodHandle.invoke()/invokeExact().
+    // They are public signature polymorphic methods, but require appendix argument
+    // which MemberName resolution doesn't handle. There's special logic on JDK side to handle them
+    // (see MethodHandles.linkMethodHandleConstant() and MethodHandles.findVirtualForMH()).
+  } else {
+    MethodHandles::resolve_MemberName(mname, caller, CHECK_(empty));
+  }
 
   // After method/field resolution succeeded, it's safe to resolve MH signature as well.
   Handle type = MethodHandles::resolve_MemberName_type(mname, caller, CHECK_(empty));
--- a/src/hotspot/share/classfile/systemDictionary.hpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/classfile/systemDictionary.hpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, 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
@@ -173,6 +173,7 @@
   do_klass(VolatileCallSite_klass,                      java_lang_invoke_VolatileCallSite,         Pre                 ) \
   /* Note: MethodHandle must be first, and VolatileCallSite last in group */                                             \
                                                                                                                          \
+  do_klass(AssertionStatusDirectives_klass,             java_lang_AssertionStatusDirectives,       Pre                 ) \
   do_klass(StringBuffer_klass,                          java_lang_StringBuffer,                    Pre                 ) \
   do_klass(StringBuilder_klass,                         java_lang_StringBuilder,                   Pre                 ) \
   do_klass(internal_Unsafe_klass,                       jdk_internal_misc_Unsafe,                  Pre                 ) \
--- a/src/hotspot/share/classfile/vmSymbols.hpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/classfile/vmSymbols.hpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, 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
@@ -251,7 +251,6 @@
   template(compiledLambdaForm_name,                   "<compiledLambdaForm>")  /*fake name*/      \
   template(star_name,                                 "*") /*not really a name*/                  \
   template(invoke_name,                               "invoke")                                   \
-  template(override_name,                             "override")                                 \
   template(parameterTypes_name,                       "parameterTypes")                           \
   template(returnType_name,                           "returnType")                               \
   template(signature_name,                            "signature")                                \
@@ -265,7 +264,6 @@
   template(parameter_annotations_name,                "parameterAnnotations")                     \
   template(annotation_default_name,                   "annotationDefault")                        \
   template(reflect_ConstantPool,                      "jdk/internal/reflect/ConstantPool")        \
-  template(ConstantPool_name,                         "constantPoolOop")                          \
   template(reflect_UnsafeStaticFieldAccessorImpl,     "jdk/internal/reflect/UnsafeStaticFieldAccessorImpl")\
   template(base_name,                                 "base")                                     \
   /* Type Annotations (JDK 8 and above) */                                                        \
@@ -304,6 +302,7 @@
   /* internal up-calls made only by the JVM, via class sun.invoke.MethodHandleNatives: */         \
   template(findMethodHandleType_name,                 "findMethodHandleType")                     \
   template(findMethodHandleType_signature,       "(Ljava/lang/Class;[Ljava/lang/Class;)Ljava/lang/invoke/MethodType;") \
+  template(invokeExact_name,                          "invokeExact")                              \
   template(linkMethodHandleConstant_name,             "linkMethodHandleConstant")                 \
   template(linkMethodHandleConstant_signature, "(Ljava/lang/Class;ILjava/lang/Class;Ljava/lang/String;Ljava/lang/Object;)Ljava/lang/invoke/MethodHandle;") \
   template(linkMethod_name,                           "linkMethod")                               \
@@ -340,8 +339,6 @@
   template(stillborn_name,                            "stillborn")                                \
   template(group_name,                                "group")                                    \
   template(daemon_name,                               "daemon")                                   \
-  template(eetop_name,                                "eetop")                                    \
-  template(thread_status_name,                        "threadStatus")                             \
   template(run_method_name,                           "run")                                      \
   template(exit_method_name,                          "exit")                                     \
   template(add_method_name,                           "add")                                      \
@@ -375,34 +372,21 @@
   template(fillInStackTrace_name,                     "fillInStackTrace")                         \
   template(getCause_name,                             "getCause")                                 \
   template(initCause_name,                            "initCause")                                \
-  template(depth_name,                                "depth")                                    \
   template(setProperty_name,                          "setProperty")                              \
   template(getProperty_name,                          "getProperty")                              \
   template(context_name,                              "context")                                  \
-  template(privilegedContext_name,                    "privilegedContext")                        \
   template(contextClassLoader_name,                   "contextClassLoader")                       \
   template(inheritedAccessControlContext_name,        "inheritedAccessControlContext")            \
-  template(isPrivileged_name,                         "isPrivileged")                             \
-  template(isAuthorized_name,                         "isAuthorized")                             \
   template(getClassContext_name,                      "getClassContext")                          \
   template(wait_name,                                 "wait")                                     \
   template(checkPackageAccess_name,                   "checkPackageAccess")                       \
-  template(stackSize_name,                            "stackSize")                                \
-  template(thread_id_name,                            "tid")                                      \
   template(newInstance0_name,                         "newInstance0")                             \
-  template(limit_name,                                "limit")                                    \
-  template(member_name,                               "member")                                   \
   template(forName_name,                              "forName")                                  \
   template(forName0_name,                             "forName0")                                 \
   template(isJavaIdentifierStart_name,                "isJavaIdentifierStart")                    \
   template(isJavaIdentifierPart_name,                 "isJavaIdentifierPart")                     \
-  template(exclusive_owner_thread_name,               "exclusiveOwnerThread")                     \
-  template(park_blocker_name,                         "parkBlocker")                              \
-  template(park_event_name,                           "nativeParkEventPointer")                   \
   template(cache_field_name,                          "cache")                                    \
   template(value_name,                                "value")                                    \
-  template(hash_name,                                 "hash")                                     \
-  template(coder_name,                                "coder")                                    \
   template(compact_strings_name,                      "COMPACT_STRINGS")                          \
   template(numberOfLeadingZeros_name,                 "numberOfLeadingZeros")                     \
   template(numberOfTrailingZeros_name,                "numberOfTrailingZeros")                    \
@@ -419,27 +403,17 @@
   template(method_name,                               "method")                                   \
   template(vmindex_name,                              "vmindex")                                  \
   template(vmcount_name,                              "vmcount")                                  \
-  template(vmentry_name,                              "vmentry")                                  \
   template(flags_name,                                "flags")                                    \
-  template(rtype_name,                                "rtype")                                    \
-  template(ptypes_name,                               "ptypes")                                   \
-  template(form_name,                                 "form")                                     \
   template(basicType_name,                            "basicType")                                \
   template(append_name,                               "append")                                   \
   template(klass_name,                                "klass")                                    \
   template(array_klass_name,                          "array_klass")                              \
-  template(memberName_name,                           "memberName")                               \
   template(mid_name,                                  "mid")                                      \
   template(cpref_name,                                "cpref")                                    \
   template(version_name,                              "version")                                  \
-  template(bci_name,                                  "bci")                                      \
   template(methodName_name,                           "methodName")                               \
   template(fileName_name,                             "fileName")                                 \
   template(lineNumber_name,                           "lineNumber")                               \
-  template(monitors_name,                             "monitors")                                 \
-  template(locals_name,                               "locals")                                   \
-  template(operands_name,                             "operands")                                 \
-  template(mode_name,                                 "mode")                                     \
   template(oop_size_name,                             "oop_size")                                 \
   template(static_oop_field_count_name,               "static_oop_field_count")                   \
   template(protection_domain_name,                    "protection_domain")                        \
@@ -447,9 +421,11 @@
   template(loader_data_name,                          "loader_data")                              \
   template(vmdependencies_name,                       "vmdependencies")                           \
   template(loader_name,                               "loader")                                   \
-  template(module_name,                               "module")                                   \
   template(getModule_name,                            "getModule")                                \
   template(input_stream_void_signature,               "(Ljava/io/InputStream;)V")                 \
+  template(input_stream_signature,                    "Ljava/io/InputStream;")                    \
+  template(print_stream_signature,                    "Ljava/io/PrintStream;")                    \
+  template(security_manager_signature,                "Ljava/lang/SecurityManager;")              \
   template(definePackage_name,                        "definePackage")                            \
   template(definePackage_signature,                   "(Ljava/lang/String;Ljava/lang/Module;)Ljava/lang/Package;") \
   template(defineOrCheckPackage_name,                 "defineOrCheckPackage")                     \
@@ -498,6 +474,7 @@
   template(short_signature,                           "S")                                        \
   template(bool_signature,                            "Z")                                        \
   template(void_signature,                            "V")                                        \
+  template(bool_array_signature,                      "[Z")                                       \
   template(byte_array_signature,                      "[B")                                       \
   template(char_array_signature,                      "[C")                                       \
   template(int_array_signature,                       "[I")                                       \
@@ -552,6 +529,7 @@
   template(object_array_signature,                    "[Ljava/lang/Object;")                                      \
   template(class_signature,                           "Ljava/lang/Class;")                                        \
   template(string_signature,                          "Ljava/lang/String;")                                       \
+  template(string_array_signature,                    "[Ljava/lang/String;")                                      \
   template(reference_signature,                       "Ljava/lang/ref/Reference;")                                \
   template(sun_misc_Cleaner_signature,                "Lsun/misc/Cleaner;")                                       \
   template(executable_signature,                      "Ljava/lang/reflect/Executable;")                           \
@@ -578,12 +556,6 @@
   /* used by ClassFormatError when class name is not known yet */                                                 \
   template(unknown_class_name,                        "<Unknown>")                                                \
                                                                                                                   \
-  /* used to identify class loaders handling parallel class loading */                                            \
-  template(parallelCapable_name,                      "parallelLockMap")                                          \
-                                                                                                                  \
-  /* used to return a class loader's unnamed module */                                                            \
-  template(unnamedModule_name,                        "unnamedModule")                                            \
-                                                                                                                  \
   /* JVM monitoring and management support */                                                                     \
   template(java_lang_StackTraceElement_array,          "[Ljava/lang/StackTraceElement;")                          \
   template(java_lang_management_ThreadState,           "java/lang/management/ThreadState")                        \
--- a/src/hotspot/share/code/compiledIC.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/code/compiledIC.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -230,10 +230,13 @@
 #ifdef ASSERT
     int index = call_info->resolved_method()->itable_index();
     assert(index == itable_index, "CallInfo pre-computes this");
-#endif //ASSERT
     InstanceKlass* k = call_info->resolved_method()->method_holder();
     assert(k->verify_itable_index(itable_index), "sanity check");
-    InlineCacheBuffer::create_transition_stub(this, k, entry);
+#endif //ASSERT
+    CompiledICHolder* holder = new CompiledICHolder(call_info->resolved_method()->method_holder(),
+                                                    call_info->resolved_klass());
+    holder->claim();
+    InlineCacheBuffer::create_transition_stub(this, holder, entry);
   } else {
     assert(call_info->call_kind() == CallInfo::vtable_call, "either itable or vtable");
     // Can be different than selected_method->vtable_index(), due to package-private etc.
@@ -517,7 +520,14 @@
 
 bool CompiledIC::is_icholder_entry(address entry) {
   CodeBlob* cb = CodeCache::find_blob_unsafe(entry);
-  return (cb != NULL && cb->is_adapter_blob());
+  if (cb != NULL && cb->is_adapter_blob()) {
+    return true;
+  }
+  // itable stubs also use CompiledICHolder
+  if (VtableStubs::is_entry_point(entry) && VtableStubs::stub_containing(entry)->is_itable_stub()) {
+    return true;
+  }
+  return false;
 }
 
 bool CompiledIC::is_icholder_call_site(virtual_call_Relocation* call_site, const CompiledMethod* cm) {
--- a/src/hotspot/share/code/compiledIC.hpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/code/compiledIC.hpp	Fri Jan 19 09:32:10 2018 -0800
@@ -45,11 +45,11 @@
 //          \                        /   \     /
 //       [4] \                      / [4] \->-/
 //            \->-  Megamorphic -<-/
-//                  (Method*)
+//              (CompiledICHolder*)
 //
-// The text in paranteses () refere to the value of the inline cache receiver (mov instruction)
+// The text in parentheses () refers to the value of the inline cache receiver (mov instruction)
 //
-// The numbers in square brackets refere to the kind of transition:
+// The numbers in square brackets refer to the kind of transition:
 // [1]: Initial fixup. Receiver it found from debug information
 // [2]: Compilation of a method
 // [3]: Recompilation of a method (note: only entry is changed. The Klass* must stay the same)
--- a/src/hotspot/share/code/compiledMethod.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/code/compiledMethod.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -404,8 +404,7 @@
     // yet be marked below. (We check this further below).
     CompiledICHolder* cichk_oop = ic->cached_icholder();
 
-    if (cichk_oop->holder_method()->method_holder()->is_loader_alive(is_alive) &&
-        cichk_oop->holder_klass()->is_loader_alive(is_alive)) {
+    if (cichk_oop->is_loader_alive(is_alive)) {
       return;
     }
   } else {
--- a/src/hotspot/share/code/dependencies.hpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/code/dependencies.hpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2018, 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
@@ -241,8 +241,18 @@
     bool is_object() const            { assert(is_valid(), "oops"); return _id < 0; }
 
     Metadata*  as_metadata(OopRecorder* rec) const    { assert(is_metadata(), "oops"); return rec->metadata_at(index()); }
-    Klass*     as_klass(OopRecorder* rec) const       { assert(as_metadata(rec)->is_klass(), "oops"); return (Klass*) as_metadata(rec); }
-    Method*    as_method(OopRecorder* rec) const      { assert(as_metadata(rec)->is_method(), "oops"); return (Method*) as_metadata(rec); }
+    Klass*     as_klass(OopRecorder* rec) const {
+      Metadata* m = as_metadata(rec);
+      assert(m != NULL, "as_metadata returned NULL");
+      assert(m->is_klass(), "oops");
+      return (Klass*) m;
+    }
+    Method*    as_method(OopRecorder* rec) const {
+      Metadata* m = as_metadata(rec);
+      assert(m != NULL, "as_metadata returned NULL");
+      assert(m->is_method(), "oops");
+      return (Method*) m;
+    }
     jobject    as_object(OopRecorder* rec) const      { assert(is_object(), "oops"); return rec->oop_at(index()); }
   };
 #endif // INCLUDE_JVMCI
--- a/src/hotspot/share/code/nmethod.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/code/nmethod.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1547,7 +1547,7 @@
         CompiledIC *ic = CompiledIC_at(&iter);
         if (ic->is_icholder_call()) {
           CompiledICHolder* cichk = ic->cached_icholder();
-          f(cichk->holder_method());
+          f(cichk->holder_metadata());
           f(cichk->holder_klass());
         } else {
           Metadata* ic_oop = ic->cached_metadata();
--- a/src/hotspot/share/gc/g1/g1CollectedHeap.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/gc/g1/g1CollectedHeap.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -445,9 +445,7 @@
   assert_heap_not_locked_and_not_at_safepoint();
   assert(!is_humongous(word_size), "we do not allow humongous TLABs");
 
-  uint dummy_gc_count_before;
-  uint dummy_gclocker_retry_count = 0;
-  return attempt_allocation(word_size, &dummy_gc_count_before, &dummy_gclocker_retry_count);
+  return attempt_allocation(word_size);
 }
 
 HeapWord*
@@ -455,62 +453,16 @@
                               bool*  gc_overhead_limit_was_exceeded) {
   assert_heap_not_locked_and_not_at_safepoint();
 
-  // Loop until the allocation is satisfied, or unsatisfied after GC.
-  for (uint try_count = 1, gclocker_retry_count = 0; /* we'll return */; try_count += 1) {
-    uint gc_count_before;
-
-    HeapWord* result = NULL;
-    if (!is_humongous(word_size)) {
-      result = attempt_allocation(word_size, &gc_count_before, &gclocker_retry_count);
-    } else {
-      result = attempt_allocation_humongous(word_size, &gc_count_before, &gclocker_retry_count);
-    }
-    if (result != NULL) {
-      return result;
-    }
-
-    // Create the garbage collection operation...
-    VM_G1CollectForAllocation op(gc_count_before, word_size);
-    op.set_allocation_context(AllocationContext::current());
-
-    // ...and get the VM thread to execute it.
-    VMThread::execute(&op);
-
-    if (op.prologue_succeeded() && op.pause_succeeded()) {
-      // If the operation was successful we'll return the result even
-      // if it is NULL. If the allocation attempt failed immediately
-      // after a Full GC, it's unlikely we'll be able to allocate now.
-      HeapWord* result = op.result();
-      if (result != NULL && !is_humongous(word_size)) {
-        // Allocations that take place on VM operations do not do any
-        // card dirtying and we have to do it here. We only have to do
-        // this for non-humongous allocations, though.
-        dirty_young_block(result, word_size);
-      }
-      return result;
-    } else {
-      if (gclocker_retry_count > GCLockerRetryAllocationCount) {
-        return NULL;
-      }
-      assert(op.result() == NULL,
-             "the result should be NULL if the VM op did not succeed");
-    }
-
-    // Give a warning if we seem to be looping forever.
-    if ((QueuedAllocationWarningCount > 0) &&
-        (try_count % QueuedAllocationWarningCount == 0)) {
-      log_warning(gc)("G1CollectedHeap::mem_allocate retries %d times", try_count);
-    }
+  if (is_humongous(word_size)) {
+    return attempt_allocation_humongous(word_size);
   }
-
-  ShouldNotReachHere();
-  return NULL;
+  return attempt_allocation(word_size);
 }
 
 HeapWord* G1CollectedHeap::attempt_allocation_slow(size_t word_size,
-                                                   AllocationContext_t context,
-                                                   uint* gc_count_before_ret,
-                                                   uint* gclocker_retry_count_ret) {
+                                                   AllocationContext_t context) {
+  ResourceMark rm; // For retrieving the thread names in log messages.
+
   // Make sure you read the note in attempt_allocation_humongous().
 
   assert_heap_not_locked_and_not_at_safepoint();
@@ -525,7 +477,7 @@
   // fails to perform the allocation. b) is the only case when we'll
   // return NULL.
   HeapWord* result = NULL;
-  for (int try_count = 1; /* we'll return */; try_count += 1) {
+  for (uint try_count = 1, gclocker_retry_count = 0; /* we'll return */; try_count += 1) {
     bool should_try_gc;
     uint gc_count_before;
 
@@ -536,30 +488,23 @@
         return result;
       }
 
-      if (GCLocker::is_active_and_needs_gc()) {
-        if (g1_policy()->can_expand_young_list()) {
-          // No need for an ergo verbose message here,
-          // can_expand_young_list() does this when it returns true.
-          result = _allocator->attempt_allocation_force(word_size, context);
-          if (result != NULL) {
-            return result;
-          }
-        }
-        should_try_gc = false;
-      } else {
-        // The GCLocker may not be active but the GCLocker initiated
-        // GC may not yet have been performed (GCLocker::needs_gc()
-        // returns true). In this case we do not try this GC and
-        // wait until the GCLocker initiated GC is performed, and
-        // then retry the allocation.
-        if (GCLocker::needs_gc()) {
-          should_try_gc = false;
-        } else {
-          // Read the GC count while still holding the Heap_lock.
-          gc_count_before = total_collections();
-          should_try_gc = true;
+      // If the GCLocker is active and we are bound for a GC, try expanding young gen.
+      // This is different to when only GCLocker::needs_gc() is set: try to avoid
+      // waiting because the GCLocker is active to not wait too long.
+      if (GCLocker::is_active_and_needs_gc() && g1_policy()->can_expand_young_list()) {
+        // No need for an ergo message here, can_expand_young_list() does this when
+        // it returns true.
+        result = _allocator->attempt_allocation_force(word_size, context);
+        if (result != NULL) {
+          return result;
         }
       }
+      // Only try a GC if the GCLocker does not signal the need for a GC. Wait until
+      // the GCLocker initiated GC has been performed and then retry. This includes
+      // the case when the GC Locker is not active but has not been performed.
+      should_try_gc = !GCLocker::needs_gc();
+      // Read the GC count while still holding the Heap_lock.
+      gc_count_before = total_collections();
     }
 
     if (should_try_gc) {
@@ -568,28 +513,33 @@
                                    GCCause::_g1_inc_collection_pause);
       if (result != NULL) {
         assert(succeeded, "only way to get back a non-NULL result");
+        log_trace(gc, alloc)("%s: Successfully scheduled collection returning " PTR_FORMAT,
+                             Thread::current()->name(), p2i(result));
         return result;
       }
 
       if (succeeded) {
-        // If we get here we successfully scheduled a collection which
-        // failed to allocate. No point in trying to allocate
-        // further. We'll just return NULL.
-        MutexLockerEx x(Heap_lock);
-        *gc_count_before_ret = total_collections();
+        // We successfully scheduled a collection which failed to allocate. No
+        // point in trying to allocate further. We'll just return NULL.
+        log_trace(gc, alloc)("%s: Successfully scheduled collection failing to allocate "
+                             SIZE_FORMAT " words", Thread::current()->name(), word_size);
         return NULL;
       }
+      log_trace(gc, alloc)("%s: Unsuccessfully scheduled collection allocating " SIZE_FORMAT " words",
+                           Thread::current()->name(), word_size);
     } else {
-      if (*gclocker_retry_count_ret > GCLockerRetryAllocationCount) {
-        MutexLockerEx x(Heap_lock);
-        *gc_count_before_ret = total_collections();
+      // Failed to schedule a collection.
+      if (gclocker_retry_count > GCLockerRetryAllocationCount) {
+        log_warning(gc, alloc)("%s: Retried waiting for GCLocker too often allocating "
+                               SIZE_FORMAT " words", Thread::current()->name(), word_size);
         return NULL;
       }
+      log_trace(gc, alloc)("%s: Stall until clear", Thread::current()->name());
       // The GCLocker is either active or the GCLocker initiated
       // GC has not yet been performed. Stall until it is and
       // then retry the allocation.
       GCLocker::stall_until_clear();
-      (*gclocker_retry_count_ret) += 1;
+      gclocker_retry_count += 1;
     }
 
     // We can reach here if we were unsuccessful in scheduling a
@@ -600,6 +550,7 @@
     // first attempt (without holding the Heap_lock) here and the
     // follow-on attempt will be at the start of the next loop
     // iteration (after taking the Heap_lock).
+
     result = _allocator->attempt_allocation(word_size, context);
     if (result != NULL) {
       return result;
@@ -608,8 +559,8 @@
     // Give a warning if we seem to be looping forever.
     if ((QueuedAllocationWarningCount > 0) &&
         (try_count % QueuedAllocationWarningCount == 0)) {
-      log_warning(gc)("G1CollectedHeap::attempt_allocation_slow() "
-                      "retries %d times", try_count);
+      log_warning(gc, alloc)("%s:  Retried allocation %u times for " SIZE_FORMAT " words",
+                             Thread::current()->name(), try_count, word_size);
     }
   }
 
@@ -830,9 +781,7 @@
   }
 }
 
-inline HeapWord* G1CollectedHeap::attempt_allocation(size_t word_size,
-                                                     uint* gc_count_before_ret,
-                                                     uint* gclocker_retry_count_ret) {
+inline HeapWord* G1CollectedHeap::attempt_allocation(size_t word_size) {
   assert_heap_not_locked_and_not_at_safepoint();
   assert(!is_humongous(word_size), "attempt_allocation() should not "
          "be called for humongous allocation requests");
@@ -841,10 +790,7 @@
   HeapWord* result = _allocator->attempt_allocation(word_size, context);
 
   if (result == NULL) {
-    result = attempt_allocation_slow(word_size,
-                                     context,
-                                     gc_count_before_ret,
-                                     gclocker_retry_count_ret);
+    result = attempt_allocation_slow(word_size, context);
   }
   assert_heap_not_locked();
   if (result != NULL) {
@@ -925,9 +871,9 @@
   decrease_used(size_used);
 }
 
-HeapWord* G1CollectedHeap::attempt_allocation_humongous(size_t word_size,
-                                                        uint* gc_count_before_ret,
-                                                        uint* gclocker_retry_count_ret) {
+HeapWord* G1CollectedHeap::attempt_allocation_humongous(size_t word_size) {
+  ResourceMark rm; // For retrieving the thread names in log messages.
+
   // The structure of this method has a lot of similarities to
   // attempt_allocation_slow(). The reason these two were not merged
   // into a single one is that such a method would require several "if
@@ -958,10 +904,11 @@
   // fails to perform the allocation. b) is the only case when we'll
   // return NULL.
   HeapWord* result = NULL;
-  for (int try_count = 1; /* we'll return */; try_count += 1) {
+  for (uint try_count = 1, gclocker_retry_count = 0; /* we'll return */; try_count += 1) {
     bool should_try_gc;
     uint gc_count_before;
 
+
     {
       MutexLockerEx x(Heap_lock);
 
@@ -975,69 +922,63 @@
         return result;
       }
 
-      if (GCLocker::is_active_and_needs_gc()) {
-        should_try_gc = false;
-      } else {
-         // The GCLocker may not be active but the GCLocker initiated
-        // GC may not yet have been performed (GCLocker::needs_gc()
-        // returns true). In this case we do not try this GC and
-        // wait until the GCLocker initiated GC is performed, and
-        // then retry the allocation.
-        if (GCLocker::needs_gc()) {
-          should_try_gc = false;
-        } else {
-          // Read the GC count while still holding the Heap_lock.
-          gc_count_before = total_collections();
-          should_try_gc = true;
-        }
-      }
+      // Only try a GC if the GCLocker does not signal the need for a GC. Wait until
+      // the GCLocker initiated GC has been performed and then retry. This includes
+      // the case when the GC Locker is not active but has not been performed.
+      should_try_gc = !GCLocker::needs_gc();
+      // Read the GC count while still holding the Heap_lock.
+      gc_count_before = total_collections();
     }
 
     if (should_try_gc) {
-      // If we failed to allocate the humongous object, we should try to
-      // do a collection pause (if we're allowed) in case it reclaims
-      // enough space for the allocation to succeed after the pause.
-
       bool succeeded;
       result = do_collection_pause(word_size, gc_count_before, &succeeded,
                                    GCCause::_g1_humongous_allocation);
       if (result != NULL) {
         assert(succeeded, "only way to get back a non-NULL result");
+        log_trace(gc, alloc)("%s: Successfully scheduled collection returning " PTR_FORMAT,
+                             Thread::current()->name(), p2i(result));
         return result;
       }
 
       if (succeeded) {
-        // If we get here we successfully scheduled a collection which
-        // failed to allocate. No point in trying to allocate
-        // further. We'll just return NULL.
-        MutexLockerEx x(Heap_lock);
-        *gc_count_before_ret = total_collections();
+        // We successfully scheduled a collection which failed to allocate. No
+        // point in trying to allocate further. We'll just return NULL.
+        log_trace(gc, alloc)("%s: Successfully scheduled collection failing to allocate "
+                             SIZE_FORMAT " words", Thread::current()->name(), word_size);
         return NULL;
       }
+      log_trace(gc, alloc)("%s: Unsuccessfully scheduled collection allocating " SIZE_FORMAT "",
+                           Thread::current()->name(), word_size);
     } else {
-      if (*gclocker_retry_count_ret > GCLockerRetryAllocationCount) {
-        MutexLockerEx x(Heap_lock);
-        *gc_count_before_ret = total_collections();
+      // Failed to schedule a collection.
+      if (gclocker_retry_count > GCLockerRetryAllocationCount) {
+        log_warning(gc, alloc)("%s: Retried waiting for GCLocker too often allocating "
+                               SIZE_FORMAT " words", Thread::current()->name(), word_size);
         return NULL;
       }
+      log_trace(gc, alloc)("%s: Stall until clear", Thread::current()->name());
       // The GCLocker is either active or the GCLocker initiated
       // GC has not yet been performed. Stall until it is and
       // then retry the allocation.
       GCLocker::stall_until_clear();
-      (*gclocker_retry_count_ret) += 1;
+      gclocker_retry_count += 1;
     }
 
+
     // We can reach here if we were unsuccessful in scheduling a
     // collection (because another thread beat us to it) or if we were
     // stalled due to the GC locker. In either can we should retry the
     // allocation attempt in case another thread successfully
-    // performed a collection and reclaimed enough space.  Give a
-    // warning if we seem to be looping forever.
+    // performed a collection and reclaimed enough space.
+    // Humongous object allocation always needs a lock, so we wait for the retry
+    // in the next iteration of the loop, unlike for the regular iteration case.
+    // Give a warning if we seem to be looping forever.
 
     if ((QueuedAllocationWarningCount > 0) &&
         (try_count % QueuedAllocationWarningCount == 0)) {
-      log_warning(gc)("G1CollectedHeap::attempt_allocation_humongous() "
-                      "retries %d times", try_count);
+      log_warning(gc, alloc)("%s: Retried allocation %u times for " SIZE_FORMAT " words",
+                             Thread::current()->name(), try_count, word_size);
     }
   }
 
@@ -1339,7 +1280,6 @@
                                     context,
                                     expect_null_mutator_alloc_region);
   if (result != NULL) {
-    assert(*gc_succeeded, "sanity");
     return result;
   }
 
@@ -1349,7 +1289,6 @@
   // do something smarter than full collection to satisfy a failed alloc.)
   result = expand_and_allocate(word_size, context);
   if (result != NULL) {
-    assert(*gc_succeeded, "sanity");
     return result;
   }
 
@@ -1401,7 +1340,6 @@
                                             succeeded);
 
   if (result != NULL) {
-    assert(*succeeded, "sanity");
     return result;
   }
 
@@ -1412,7 +1350,6 @@
   // space available is large enough for the allocation, then a more
   // complete compaction phase than we've tried so far might be
   // appropriate.
-  assert(*succeeded, "sanity");
   return NULL;
 }
 
@@ -2147,7 +2084,7 @@
   // This notify_all() will ensure that a thread that called
   // System.gc() with (with ExplicitGCInvokesConcurrent set or not)
   // and it's waiting for a full GC to finish will be woken up. It is
-  // waiting in VM_G1IncCollectionPause::doit_epilogue().
+  // waiting in VM_G1CollectForAllocation::doit_epilogue().
   FullGCCount_lock->notify_all();
 }
 
@@ -2175,13 +2112,12 @@
       // Schedule an initial-mark evacuation pause that will start a
       // concurrent cycle. We're setting word_size to 0 which means that
       // we are not requesting a post-GC allocation.
-      VM_G1IncCollectionPause op(gc_count_before,
-                                 0,     /* word_size */
-                                 true,  /* should_initiate_conc_mark */
-                                 g1_policy()->max_pause_time_ms(),
-                                 cause);
-      op.set_allocation_context(AllocationContext::current());
-
+      VM_G1CollectForAllocation op(0,     /* word_size */
+                                   gc_count_before,
+                                   cause,
+                                   true,  /* should_initiate_conc_mark */
+                                   g1_policy()->max_pause_time_ms(),
+                                   AllocationContext::current());
       VMThread::execute(&op);
       if (!op.pause_succeeded()) {
         if (old_marking_count_before == _old_marking_cycles_started) {
@@ -2204,11 +2140,12 @@
 
         // Schedule a standard evacuation pause. We're setting word_size
         // to 0 which means that we are not requesting a post-GC allocation.
-        VM_G1IncCollectionPause op(gc_count_before,
-                                   0,     /* word_size */
-                                   false, /* should_initiate_conc_mark */
-                                   g1_policy()->max_pause_time_ms(),
-                                   cause);
+        VM_G1CollectForAllocation op(0,     /* word_size */
+                                     gc_count_before,
+                                     cause,
+                                     false, /* should_initiate_conc_mark */
+                                     g1_policy()->max_pause_time_ms(),
+                                     AllocationContext::current());
         VMThread::execute(&op);
       } else {
         // Schedule a Full GC.
@@ -2619,13 +2556,12 @@
                                                bool* succeeded,
                                                GCCause::Cause gc_cause) {
   assert_heap_not_locked_and_not_at_safepoint();
-  VM_G1IncCollectionPause op(gc_count_before,
-                             word_size,
-                             false, /* should_initiate_conc_mark */
-                             g1_policy()->max_pause_time_ms(),
-                             gc_cause);
-
-  op.set_allocation_context(AllocationContext::current());
+  VM_G1CollectForAllocation op(word_size,
+                               gc_count_before,
+                               gc_cause,
+                               false, /* should_initiate_conc_mark */
+                               g1_policy()->max_pause_time_ms(),
+                               AllocationContext::current());
   VMThread::execute(&op);
 
   HeapWord* result = op.result();
--- a/src/hotspot/share/gc/g1/g1CollectedHeap.hpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/gc/g1/g1CollectedHeap.hpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2018, 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
@@ -125,7 +125,6 @@
   friend class VM_CollectForMetadataAllocation;
   friend class VM_G1CollectForAllocation;
   friend class VM_G1CollectFull;
-  friend class VM_G1IncCollectionPause;
   friend class VMStructs;
   friend class MutatorAllocRegion;
   friend class G1FullCollector;
@@ -454,35 +453,20 @@
   virtual HeapWord* mem_allocate(size_t word_size,
                                  bool*  gc_overhead_limit_was_exceeded);
 
-  // The following three methods take a gc_count_before_ret
-  // parameter which is used to return the GC count if the method
-  // returns NULL. Given that we are required to read the GC count
-  // while holding the Heap_lock, and these paths will take the
-  // Heap_lock at some point, it's easier to get them to read the GC
-  // count while holding the Heap_lock before they return NULL instead
-  // of the caller (namely: mem_allocate()) having to also take the
-  // Heap_lock just to read the GC count.
-
   // First-level mutator allocation attempt: try to allocate out of
   // the mutator alloc region without taking the Heap_lock. This
   // should only be used for non-humongous allocations.
-  inline HeapWord* attempt_allocation(size_t word_size,
-                                      uint* gc_count_before_ret,
-                                      uint* gclocker_retry_count_ret);
+  inline HeapWord* attempt_allocation(size_t word_size);
 
   // Second-level mutator allocation attempt: take the Heap_lock and
   // retry the allocation attempt, potentially scheduling a GC
   // pause. This should only be used for non-humongous allocations.
   HeapWord* attempt_allocation_slow(size_t word_size,
-                                    AllocationContext_t context,
-                                    uint* gc_count_before_ret,
-                                    uint* gclocker_retry_count_ret);
+                                    AllocationContext_t context);
 
   // Takes the Heap_lock and attempts a humongous allocation. It can
   // potentially schedule a GC pause.
-  HeapWord* attempt_allocation_humongous(size_t word_size,
-                                         uint* gc_count_before_ret,
-                                         uint* gclocker_retry_count_ret);
+  HeapWord* attempt_allocation_humongous(size_t word_size);
 
   // Allocation attempt that should be called during safepoints (e.g.,
   // at the end of a successful GC). expect_null_mutator_alloc_region
@@ -1078,6 +1062,11 @@
     return _hrm.available() == 0;
   }
 
+  // Returns whether there are any regions left in the heap for allocation.
+  bool has_regions_left_for_allocation() const {
+    return !is_maximal_no_gc() || num_free_regions() != 0;
+  }
+
   // The current number of regions in the heap.
   uint num_regions() const { return _hrm.length(); }
 
--- a/src/hotspot/share/gc/g1/g1OopClosures.inline.hpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/gc/g1/g1OopClosures.inline.hpp	Fri Jan 19 09:32:10 2018 -0800
@@ -33,6 +33,7 @@
 #include "gc/g1/heapRegion.inline.hpp"
 #include "gc/g1/heapRegionRemSet.hpp"
 #include "memory/iterator.inline.hpp"
+#include "oops/access.inline.hpp"
 #include "runtime/prefetch.inline.hpp"
 
 template <class T>
@@ -87,13 +88,13 @@
 
 template <class T>
 inline void G1CMOopClosure::do_oop_nv(T* p) {
-  oop obj = oopDesc::load_decode_heap_oop(p);
+  oop obj = RawAccess<MO_VOLATILE>::oop_load(p);
   _task->deal_with_reference(obj);
 }
 
 template <class T>
 inline void G1RootRegionScanClosure::do_oop_nv(T* p) {
-  T heap_oop = oopDesc::load_heap_oop(p);
+  T heap_oop = RawAccess<MO_VOLATILE>::oop_load(p);
   if (oopDesc::is_null(heap_oop)) {
     return;
   }
@@ -124,7 +125,7 @@
 
 template <class T>
 inline void G1ConcurrentRefineOopClosure::do_oop_nv(T* p) {
-  T o = oopDesc::load_heap_oop(p);
+  T o = RawAccess<MO_VOLATILE>::oop_load(p);
   if (oopDesc::is_null(o)) {
     return;
   }
--- a/src/hotspot/share/gc/g1/g1SATBCardTableModRefBS.inline.hpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/gc/g1/g1SATBCardTableModRefBS.inline.hpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,7 +27,6 @@
 
 #include "gc/shared/accessBarrierSupport.inline.hpp"
 #include "gc/g1/g1SATBCardTableModRefBS.hpp"
-#include "oops/oop.inline.hpp"
 
 template <DecoratorSet decorators, typename T>
 inline void G1SATBCardTableModRefBS::write_ref_field_pre(T* field) {
--- a/src/hotspot/share/gc/g1/vm_operations_g1.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/gc/g1/vm_operations_g1.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2018, 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,34 +33,21 @@
 #include "gc/shared/isGCActiveMark.hpp"
 #include "runtime/interfaceSupport.hpp"
 
-VM_G1CollectForAllocation::VM_G1CollectForAllocation(uint gc_count_before,
-                                                     size_t word_size)
-  : VM_G1OperationWithAllocRequest(gc_count_before, word_size,
-                                   GCCause::_allocation_failure) {
-  guarantee(word_size != 0, "An allocation should always be requested with this operation.");
-}
-
-void VM_G1CollectForAllocation::doit() {
-  G1CollectedHeap* g1h = G1CollectedHeap::heap();
-  GCCauseSetter x(g1h, _gc_cause);
-
-  _result = g1h->satisfy_failed_allocation(_word_size, allocation_context(), &_pause_succeeded);
-  assert(_result == NULL || _pause_succeeded,
-         "if we get back a result, the pause should have succeeded");
-}
-
 void VM_G1CollectFull::doit() {
   G1CollectedHeap* g1h = G1CollectedHeap::heap();
   GCCauseSetter x(g1h, _gc_cause);
   g1h->do_full_collection(false /* clear_all_soft_refs */);
 }
 
-VM_G1IncCollectionPause::VM_G1IncCollectionPause(uint           gc_count_before,
-                                                 size_t         word_size,
-                                                 bool           should_initiate_conc_mark,
-                                                 double         target_pause_time_ms,
-                                                 GCCause::Cause gc_cause)
-  : VM_G1OperationWithAllocRequest(gc_count_before, word_size, gc_cause),
+VM_G1CollectForAllocation::VM_G1CollectForAllocation(size_t         word_size,
+                                                     uint           gc_count_before,
+                                                     GCCause::Cause gc_cause,
+                                                     bool           should_initiate_conc_mark,
+                                                     double         target_pause_time_ms,
+                                                     AllocationContext_t allocation_context)
+  : VM_CollectForAllocation(word_size, gc_count_before, gc_cause),
+    _pause_succeeded(false),
+    _allocation_context(allocation_context),
     _should_initiate_conc_mark(should_initiate_conc_mark),
     _target_pause_time_ms(target_pause_time_ms),
     _should_retry_gc(false),
@@ -71,8 +58,8 @@
   _gc_cause = gc_cause;
 }
 
-bool VM_G1IncCollectionPause::doit_prologue() {
-  bool res = VM_G1OperationWithAllocRequest::doit_prologue();
+bool VM_G1CollectForAllocation::doit_prologue() {
+  bool res = VM_CollectForAllocation::doit_prologue();
   if (!res) {
     if (_should_initiate_conc_mark) {
       // The prologue can fail for a couple of reasons. The first is that another GC
@@ -87,7 +74,7 @@
   return res;
 }
 
-void VM_G1IncCollectionPause::doit() {
+void VM_G1CollectForAllocation::doit() {
   G1CollectedHeap* g1h = G1CollectedHeap::heap();
   assert(!_should_initiate_conc_mark || g1h->should_do_concurrent_full_gc(_gc_cause),
       "only a GC locker, a System.gc(), stats update, whitebox, or a hum allocation induced GC should start a cycle");
@@ -95,7 +82,7 @@
   if (_word_size > 0) {
     // An allocation has been requested. So, try to do that first.
     _result = g1h->attempt_allocation_at_safepoint(_word_size,
-                                                   allocation_context(),
+                                                   _allocation_context,
                                                    false /* expect_null_cur_alloc_region */);
     if (_result != NULL) {
       // If we can successfully allocate before we actually do the
@@ -144,27 +131,38 @@
     }
   }
 
-  _pause_succeeded =
-    g1h->do_collection_pause_at_safepoint(_target_pause_time_ms);
-  if (_pause_succeeded && _word_size > 0) {
-    // An allocation had been requested.
-    _result = g1h->attempt_allocation_at_safepoint(_word_size,
-                                                   allocation_context(),
-                                                   true /* expect_null_cur_alloc_region */);
+  // Try a partial collection of some kind.
+  _pause_succeeded = g1h->do_collection_pause_at_safepoint(_target_pause_time_ms);
+
+  if (_pause_succeeded) {
+    if (_word_size > 0) {
+      // An allocation had been requested. Do it, eventually trying a stronger
+      // kind of GC.
+      _result = g1h->satisfy_failed_allocation(_word_size, _allocation_context, &_pause_succeeded);
+    } else {
+      bool should_upgrade_to_full = !g1h->should_do_concurrent_full_gc(_gc_cause) &&
+                                    !g1h->has_regions_left_for_allocation();
+      if (should_upgrade_to_full) {
+        // There has been a request to perform a GC to free some space. We have no
+        // information on how much memory has been asked for. In case there are
+        // absolutely no regions left to allocate into, do a maximally compacting full GC.
+        log_info(gc, ergo)("Attempting maximally compacting collection");
+        _pause_succeeded = g1h->do_full_collection(false, /* explicit gc */
+                                                   true   /* clear_all_soft_refs */);
+      }
+    }
+    guarantee(_pause_succeeded, "Elevated collections during the safepoint must always succeed.");
   } else {
     assert(_result == NULL, "invariant");
-    if (!_pause_succeeded) {
-      // Another possible reason reason for the pause to not be successful
-      // is that, again, the GC locker is active (and has become active
-      // since the prologue was executed). In this case we should retry
-      // the pause after waiting for the GC locker to become inactive.
-      _should_retry_gc = true;
-    }
+    // The only reason for the pause to not be successful is that, the GC locker is
+    // active (or has become active since the prologue was executed). In this case
+    // we should retry the pause after waiting for the GC locker to become inactive.
+    _should_retry_gc = true;
   }
 }
 
-void VM_G1IncCollectionPause::doit_epilogue() {
-  VM_G1OperationWithAllocRequest::doit_epilogue();
+void VM_G1CollectForAllocation::doit_epilogue() {
+  VM_CollectForAllocation::doit_epilogue();
 
   // If the pause was initiated by a System.gc() and
   // +ExplicitGCInvokesConcurrent, we have to wait here for the cycle
--- a/src/hotspot/share/gc/g1/vm_operations_g1.hpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/gc/g1/vm_operations_g1.hpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2018, 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
@@ -32,26 +32,8 @@
 // VM_operations for the G1 collector.
 // VM_GC_Operation:
 //   - VM_CGC_Operation
+//   - VM_G1CollectForAllocation
 //   - VM_G1CollectFull
-//   - VM_G1OperationWithAllocRequest
-//     - VM_G1CollectForAllocation
-//     - VM_G1IncCollectionPause
-
-class VM_G1OperationWithAllocRequest : public VM_CollectForAllocation {
-protected:
-  bool      _pause_succeeded;
-  AllocationContext_t _allocation_context;
-
-public:
-  VM_G1OperationWithAllocRequest(uint           gc_count_before,
-                                 size_t         word_size,
-                                 GCCause::Cause gc_cause)
-    : VM_CollectForAllocation(word_size, gc_count_before, gc_cause),
-      _pause_succeeded(false) {}
-  bool pause_succeeded() { return _pause_succeeded; }
-  void set_allocation_context(AllocationContext_t context) { _allocation_context = context; }
-  AllocationContext_t  allocation_context() { return _allocation_context; }
-};
 
 class VM_G1CollectFull: public VM_GC_Operation {
 public:
@@ -62,41 +44,35 @@
   virtual VMOp_Type type() const { return VMOp_G1CollectFull; }
   virtual void doit();
   virtual const char* name() const {
-    return "full garbage-first collection";
+    return "G1 Full collection";
   }
 };
 
-class VM_G1CollectForAllocation: public VM_G1OperationWithAllocRequest {
-public:
-  VM_G1CollectForAllocation(uint         gc_count_before,
-                            size_t       word_size);
-  virtual VMOp_Type type() const { return VMOp_G1CollectForAllocation; }
-  virtual void doit();
-  virtual const char* name() const {
-    return "garbage-first collection to satisfy allocation";
-  }
-};
+class VM_G1CollectForAllocation: public VM_CollectForAllocation {
+private:
+  bool      _pause_succeeded;
+  AllocationContext_t _allocation_context;
 
-class VM_G1IncCollectionPause: public VM_G1OperationWithAllocRequest {
-private:
   bool         _should_initiate_conc_mark;
   bool         _should_retry_gc;
   double       _target_pause_time_ms;
   uint         _old_marking_cycles_completed_before;
 public:
-  VM_G1IncCollectionPause(uint           gc_count_before,
-                          size_t         word_size,
-                          bool           should_initiate_conc_mark,
-                          double         target_pause_time_ms,
-                          GCCause::Cause gc_cause);
-  virtual VMOp_Type type() const { return VMOp_G1IncCollectionPause; }
+  VM_G1CollectForAllocation(size_t         word_size,
+                            uint           gc_count_before,
+                            GCCause::Cause gc_cause,
+                            bool           should_initiate_conc_mark,
+                            double         target_pause_time_ms,
+                            AllocationContext_t allocation_context);
+  virtual VMOp_Type type() const { return VMOp_G1CollectForAllocation; }
   virtual bool doit_prologue();
   virtual void doit();
   virtual void doit_epilogue();
   virtual const char* name() const {
-    return "garbage-first incremental collection pause";
+    return "G1 collect for allocation";
   }
   bool should_retry_gc() const { return _should_retry_gc; }
+  bool pause_succeeded() { return _pause_succeeded; }
 };
 
 // Concurrent GC stop-the-world operations such as remark and cleanup;
--- a/src/hotspot/share/gc/shared/barrierSet.hpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/gc/shared/barrierSet.hpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2018, 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
@@ -147,9 +147,8 @@
   // 3) Provide specializations for BarrierSet::GetName and BarrierSet::GetType.
   template <DecoratorSet decorators, typename BarrierSetT>
   class AccessBarrier: protected RawAccessBarrier<decorators> {
-  protected:
+  private:
     typedef RawAccessBarrier<decorators> Raw;
-    typedef typename BarrierSetT::template AccessBarrier<decorators> CRTPAccessBarrier;
 
   public:
     // Primitive heap accesses. These accessors get resolved when
--- a/src/hotspot/share/interpreter/interpreterRuntime.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/interpreter/interpreterRuntime.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -804,7 +804,7 @@
   // it is not an interface.  The receiver for invokespecial calls within interface
   // methods must be checked for every call.
   InstanceKlass* sender = pool->pool_holder();
-  sender = sender->is_anonymous() ? sender->host_klass() : sender;
+  sender = sender->has_host_klass() ? sender->host_klass() : sender;
 
   switch (info.call_kind()) {
   case CallInfo::direct_call:
@@ -822,6 +822,7 @@
   case CallInfo::itable_call:
     cp_cache_entry->set_itable_call(
       bytecode,
+      info.resolved_klass(),
       info.resolved_method(),
       info.itable_index());
     break;
--- a/src/hotspot/share/jvmci/jvmciCompilerToVM.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/jvmci/jvmciCompilerToVM.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2018, 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
@@ -1433,6 +1433,7 @@
               Deoptimization::reassign_fields(fst.current(), fst.register_map(), scope->objects(), realloc_failures, false);
 
               GrowableArray<ScopeValue*>* local_values = scope->locals();
+              assert(local_values != NULL, "NULL locals");
               typeArrayOop array_oop = oopFactory::new_boolArray(local_values->length(), CHECK_NULL);
               typeArrayHandle array(THREAD, array_oop);
               for (int i = 0; i < local_values->length(); i++) {
@@ -1660,7 +1661,6 @@
 
     GrowableArray<ScopeValue*>* scopeLocals = cvf->scope()->locals();
     StackValueCollection* locals = cvf->locals();
-
     if (locals != NULL) {
       for (int i2 = 0; i2 < locals->size(); i2++) {
         StackValue* var = locals->at(i2);
@@ -1671,6 +1671,27 @@
         }
       }
     }
+
+    GrowableArray<ScopeValue*>* scopeExpressions = cvf->scope()->expressions();
+    StackValueCollection* expressions = cvf->expressions();
+    if (expressions != NULL) {
+      for (int i2 = 0; i2 < expressions->size(); i2++) {
+        StackValue* var = expressions->at(i2);
+        if (var->type() == T_OBJECT && scopeExpressions->at(i2)->is_object()) {
+          jvalue val;
+          val.l = (jobject) expressions->at(i2)->get_obj()();
+          cvf->update_stack(T_OBJECT, i2, val);
+        }
+      }
+    }
+
+    GrowableArray<MonitorValue*>* scopeMonitors = cvf->scope()->monitors();
+    GrowableArray<MonitorInfo*>* monitors = cvf->monitors();
+    if (monitors != NULL) {
+      for (int i2 = 0; i2 < monitors->length(); i2++) {
+        cvf->update_monitor(i2, monitors->at(i2));
+      }
+    }
   }
 
   // all locals are materialized by now
--- a/src/hotspot/share/jvmci/jvmciJavaClasses.hpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/jvmci/jvmciJavaClasses.hpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2018, 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
@@ -351,7 +351,7 @@
     static type name() {                                                                                       \
       assert(klassName::klass() != NULL && klassName::klass()->is_linked(), "Class not yet linked: " #klassName); \
       InstanceKlass* ik = klassName::klass();                                                                  \
-      address addr = ik->static_field_addr(_##name##_offset - InstanceMirrorKlass::offset_of_static_fields()); \
+      address addr = ik->static_field_addr(_##name##_offset);                                                  \
       oop result = HeapAccess<>::oop_load((HeapWord*)addr);                                                    \
       return type(result);                                                                                     \
     }                                                                                                          \
@@ -359,7 +359,7 @@
       assert(klassName::klass() != NULL && klassName::klass()->is_linked(), "Class not yet linked: " #klassName); \
       assert(klassName::klass() != NULL, "Class not yet loaded: " #klassName);                                 \
       InstanceKlass* ik = klassName::klass();                                                                  \
-      address addr = ik->static_field_addr(_##name##_offset - InstanceMirrorKlass::offset_of_static_fields()); \
+      address addr = ik->static_field_addr(_##name##_offset);                                                  \
       HeapAccess<>::oop_store((HeapWord*)addr, x);                                                             \
     }
 #define STATIC_PRIMITIVE_FIELD(klassName, name, jtypename)                                                     \
@@ -367,13 +367,13 @@
     static jtypename name() {                                                                                  \
       assert(klassName::klass() != NULL && klassName::klass()->is_linked(), "Class not yet linked: " #klassName); \
       InstanceKlass* ik = klassName::klass();                                                                  \
-      address addr = ik->static_field_addr(_##name##_offset - InstanceMirrorKlass::offset_of_static_fields()); \
+      address addr = ik->static_field_addr(_##name##_offset);                                                  \
       return HeapAccess<>::load((jtypename*)addr);                                                             \
     }                                                                                                          \
     static void set_##name(jtypename x) {                                                                      \
       assert(klassName::klass() != NULL && klassName::klass()->is_linked(), "Class not yet linked: " #klassName); \
       InstanceKlass* ik = klassName::klass();                                                                  \
-      address addr = ik->static_field_addr(_##name##_offset - InstanceMirrorKlass::offset_of_static_fields()); \
+      address addr = ik->static_field_addr(_##name##_offset);                                                  \
       HeapAccess<>::store((jtypename*)addr, x);                                                                \
     }
 
--- a/src/hotspot/share/oops/access.hpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/oops/access.hpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2017, 2018, 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
@@ -342,7 +342,7 @@
   template <DecoratorSet expected_mo_decorators>
   static void verify_primitive_decorators() {
     const DecoratorSet primitive_decorators = (AS_DECORATOR_MASK ^ AS_NO_KEEPALIVE) | IN_HEAP |
-                                               IN_HEAP_ARRAY | MO_DECORATOR_MASK;
+                                               IN_HEAP_ARRAY;
     verify_decorators<expected_mo_decorators | primitive_decorators>();
   }
 
@@ -350,7 +350,7 @@
   static void verify_oop_decorators() {
     const DecoratorSet oop_decorators = AS_DECORATOR_MASK | IN_DECORATOR_MASK |
                                         (ON_DECORATOR_MASK ^ ON_UNKNOWN_OOP_REF) | // no unknown oop refs outside of the heap
-                                        OOP_DECORATOR_MASK | MO_DECORATOR_MASK;
+                                        OOP_DECORATOR_MASK;
     verify_decorators<expected_mo_decorators | oop_decorators>();
   }
 
@@ -358,8 +358,7 @@
   static void verify_heap_oop_decorators() {
     const DecoratorSet heap_oop_decorators = AS_DECORATOR_MASK | ON_DECORATOR_MASK |
                                              OOP_DECORATOR_MASK | (IN_DECORATOR_MASK ^
-                                                                  (IN_ROOT ^ IN_CONCURRENT_ROOT)) | // no root accesses in the heap
-                                             MO_DECORATOR_MASK;
+                                                                   (IN_ROOT | IN_CONCURRENT_ROOT)); // no root accesses in the heap
     verify_decorators<expected_mo_decorators | heap_oop_decorators>();
   }
 
--- a/src/hotspot/share/oops/access.inline.hpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/oops/access.inline.hpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2017, 2018, 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
@@ -491,11 +491,12 @@
   // not possible.
   struct PreRuntimeDispatch: AllStatic {
     template<DecoratorSet decorators>
-    static bool can_hardwire_raw() {
-      return !HasDecorator<decorators, INTERNAL_VALUE_IS_OOP>::value || // primitive access
-             !HasDecorator<decorators, INTERNAL_CONVERT_COMPRESSED_OOP>::value || // don't care about compressed oops (oop* address)
-             HasDecorator<decorators, INTERNAL_RT_USE_COMPRESSED_OOPS>::value; // we can infer we use compressed oops (narrowOop* address)
-    }
+    struct CanHardwireRaw: public IntegralConstant<
+      bool,
+      !HasDecorator<decorators, INTERNAL_VALUE_IS_OOP>::value || // primitive access
+      !HasDecorator<decorators, INTERNAL_CONVERT_COMPRESSED_OOP>::value || // don't care about compressed oops (oop* address)
+      HasDecorator<decorators, INTERNAL_RT_USE_COMPRESSED_OOPS>::value> // we can infer we use compressed oops (narrowOop* address)
+    {};
 
     static const DecoratorSet convert_compressed_oops = INTERNAL_RT_USE_COMPRESSED_OOPS | INTERNAL_CONVERT_COMPRESSED_OOP;
 
@@ -507,16 +508,21 @@
 
     template <DecoratorSet decorators, typename T>
     inline static typename EnableIf<
-      HasDecorator<decorators, AS_RAW>::value>::type
+      HasDecorator<decorators, AS_RAW>::value && CanHardwireRaw<decorators>::value>::type
     store(void* addr, T value) {
       typedef RawAccessBarrier<decorators & RAW_DECORATOR_MASK> Raw;
-      if (can_hardwire_raw<decorators>()) {
-        if (HasDecorator<decorators, INTERNAL_VALUE_IS_OOP>::value) {
-          Raw::oop_store(addr, value);
-        } else {
-          Raw::store(addr, value);
-        }
-      } else if (UseCompressedOops) {
+      if (HasDecorator<decorators, INTERNAL_VALUE_IS_OOP>::value) {
+        Raw::oop_store(addr, value);
+      } else {
+        Raw::store(addr, value);
+      }
+    }
+
+    template <DecoratorSet decorators, typename T>
+    inline static typename EnableIf<
+      HasDecorator<decorators, AS_RAW>::value && !CanHardwireRaw<decorators>::value>::type
+    store(void* addr, T value) {
+      if (UseCompressedOops) {
         const DecoratorSet expanded_decorators = decorators | convert_compressed_oops;
         PreRuntimeDispatch::store<expanded_decorators>(addr, value);
       } else {
@@ -558,16 +564,21 @@
 
     template <DecoratorSet decorators, typename T>
     inline static typename EnableIf<
-      HasDecorator<decorators, AS_RAW>::value, T>::type
+      HasDecorator<decorators, AS_RAW>::value && CanHardwireRaw<decorators>::value, T>::type
     load(void* addr) {
       typedef RawAccessBarrier<decorators & RAW_DECORATOR_MASK> Raw;
-      if (can_hardwire_raw<decorators>()) {
-        if (HasDecorator<decorators, INTERNAL_VALUE_IS_OOP>::value) {
-          return Raw::template oop_load<T>(addr);
-        } else {
-          return Raw::template load<T>(addr);
-        }
-      } else if (UseCompressedOops) {
+      if (HasDecorator<decorators, INTERNAL_VALUE_IS_OOP>::value) {
+        return Raw::template oop_load<T>(addr);
+      } else {
+        return Raw::template load<T>(addr);
+      }
+    }
+
+    template <DecoratorSet decorators, typename T>
+    inline static typename EnableIf<
+      HasDecorator<decorators, AS_RAW>::value && !CanHardwireRaw<decorators>::value, T>::type
+    load(void* addr) {
+      if (UseCompressedOops) {
         const DecoratorSet expanded_decorators = decorators | convert_compressed_oops;
         return PreRuntimeDispatch::load<expanded_decorators, T>(addr);
       } else {
@@ -609,16 +620,21 @@
 
     template <DecoratorSet decorators, typename T>
     inline static typename EnableIf<
-      HasDecorator<decorators, AS_RAW>::value, T>::type
+      HasDecorator<decorators, AS_RAW>::value && CanHardwireRaw<decorators>::value, T>::type
     atomic_cmpxchg(T new_value, void* addr, T compare_value) {
       typedef RawAccessBarrier<decorators & RAW_DECORATOR_MASK> Raw;
-      if (can_hardwire_raw<decorators>()) {
-        if (HasDecorator<decorators, INTERNAL_VALUE_IS_OOP>::value) {
-          return Raw::oop_atomic_cmpxchg(new_value, addr, compare_value);
-        } else {
-          return Raw::atomic_cmpxchg(new_value, addr, compare_value);
-        }
-      } else if (UseCompressedOops) {
+      if (HasDecorator<decorators, INTERNAL_VALUE_IS_OOP>::value) {
+        return Raw::oop_atomic_cmpxchg(new_value, addr, compare_value);
+      } else {
+        return Raw::atomic_cmpxchg(new_value, addr, compare_value);
+      }
+    }
+
+    template <DecoratorSet decorators, typename T>
+    inline static typename EnableIf<
+      HasDecorator<decorators, AS_RAW>::value && !CanHardwireRaw<decorators>::value, T>::type
+    atomic_cmpxchg(T new_value, void* addr, T compare_value) {
+      if (UseCompressedOops) {
         const DecoratorSet expanded_decorators = decorators | convert_compressed_oops;
         return PreRuntimeDispatch::atomic_cmpxchg<expanded_decorators>(new_value, addr, compare_value);
       } else {
@@ -661,16 +677,21 @@
 
     template <DecoratorSet decorators, typename T>
     inline static typename EnableIf<
-      HasDecorator<decorators, AS_RAW>::value, T>::type
+      HasDecorator<decorators, AS_RAW>::value && CanHardwireRaw<decorators>::value, T>::type
     atomic_xchg(T new_value, void* addr) {
       typedef RawAccessBarrier<decorators & RAW_DECORATOR_MASK> Raw;
-      if (can_hardwire_raw<decorators>()) {
-        if (HasDecorator<decorators, INTERNAL_VALUE_IS_OOP>::value) {
-          return Raw::oop_atomic_xchg(new_value, addr);
-        } else {
-          return Raw::atomic_xchg(new_value, addr);
-        }
-      } else if (UseCompressedOops) {
+      if (HasDecorator<decorators, INTERNAL_VALUE_IS_OOP>::value) {
+        return Raw::oop_atomic_xchg(new_value, addr);
+      } else {
+        return Raw::atomic_xchg(new_value, addr);
+      }
+    }
+
+    template <DecoratorSet decorators, typename T>
+    inline static typename EnableIf<
+      HasDecorator<decorators, AS_RAW>::value && !CanHardwireRaw<decorators>::value, T>::type
+    atomic_xchg(T new_value, void* addr) {
+      if (UseCompressedOops) {
         const DecoratorSet expanded_decorators = decorators | convert_compressed_oops;
         return PreRuntimeDispatch::atomic_xchg<expanded_decorators>(new_value, addr);
       } else {
@@ -798,6 +819,13 @@
   }
 
   template <DecoratorSet decorators>
+  inline void store_reduce_types(narrowOop* addr, narrowOop value) {
+    const DecoratorSet expanded_decorators = decorators | INTERNAL_CONVERT_COMPRESSED_OOP |
+                                             INTERNAL_RT_USE_COMPRESSED_OOPS;
+    PreRuntimeDispatch::store<expanded_decorators>(addr, value);
+  }
+
+  template <DecoratorSet decorators>
   inline void store_reduce_types(HeapWord* addr, oop value) {
     const DecoratorSet expanded_decorators = decorators | INTERNAL_CONVERT_COMPRESSED_OOP;
     PreRuntimeDispatch::store<expanded_decorators>(addr, value);
@@ -816,7 +844,16 @@
   }
 
   template <DecoratorSet decorators>
-  inline oop atomic_cmpxchg_reduce_types(oop new_value, HeapWord* addr, oop compare_value) {
+  inline narrowOop atomic_cmpxchg_reduce_types(narrowOop new_value, narrowOop* addr, narrowOop compare_value) {
+    const DecoratorSet expanded_decorators = decorators | INTERNAL_CONVERT_COMPRESSED_OOP |
+                                             INTERNAL_RT_USE_COMPRESSED_OOPS;
+    return PreRuntimeDispatch::atomic_cmpxchg<expanded_decorators>(new_value, addr, compare_value);
+  }
+
+  template <DecoratorSet decorators>
+  inline oop atomic_cmpxchg_reduce_types(oop new_value,
+                                         HeapWord* addr,
+                                         oop compare_value) {
     const DecoratorSet expanded_decorators = decorators | INTERNAL_CONVERT_COMPRESSED_OOP;
     return PreRuntimeDispatch::atomic_cmpxchg<expanded_decorators>(new_value, addr, compare_value);
   }
@@ -835,6 +872,13 @@
   }
 
   template <DecoratorSet decorators>
+  inline narrowOop atomic_xchg_reduce_types(narrowOop new_value, narrowOop* addr) {
+    const DecoratorSet expanded_decorators = decorators | INTERNAL_CONVERT_COMPRESSED_OOP |
+                                             INTERNAL_RT_USE_COMPRESSED_OOPS;
+    return PreRuntimeDispatch::atomic_xchg<expanded_decorators>(new_value, addr);
+  }
+
+  template <DecoratorSet decorators>
   inline oop atomic_xchg_reduce_types(oop new_value, HeapWord* addr) {
     const DecoratorSet expanded_decorators = decorators | INTERNAL_CONVERT_COMPRESSED_OOP;
     return PreRuntimeDispatch::atomic_xchg<expanded_decorators>(new_value, addr);
@@ -846,9 +890,10 @@
   }
 
   template <DecoratorSet decorators, typename T>
-  inline oop load_reduce_types(narrowOop* addr) {
-    const DecoratorSet expanded_decorators = decorators | INTERNAL_CONVERT_COMPRESSED_OOP | INTERNAL_RT_USE_COMPRESSED_OOPS;
-    return PreRuntimeDispatch::load<expanded_decorators, oop>(addr);
+  inline typename OopOrNarrowOop<T>::type load_reduce_types(narrowOop* addr) {
+    const DecoratorSet expanded_decorators = decorators | INTERNAL_CONVERT_COMPRESSED_OOP |
+                                             INTERNAL_RT_USE_COMPRESSED_OOPS;
+    return PreRuntimeDispatch::load<expanded_decorators, typename OopOrNarrowOop<T>::type>(addr);
   }
 
   template <DecoratorSet decorators, typename T>
--- a/src/hotspot/share/oops/accessBackend.hpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/oops/accessBackend.hpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2017, 2018, 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,6 +28,7 @@
 #include "metaprogramming/conditional.hpp"
 #include "metaprogramming/enableIf.hpp"
 #include "metaprogramming/integralConstant.hpp"
+#include "metaprogramming/isSame.hpp"
 #include "utilities/debug.hpp"
 #include "utilities/globalDefinitions.hpp"
 
@@ -54,11 +55,11 @@
     BARRIER_CLONE
   };
 
-  template <DecoratorSet decorators>
+  template <DecoratorSet decorators, typename T>
   struct MustConvertCompressedOop: public IntegralConstant<bool,
     HasDecorator<decorators, INTERNAL_VALUE_IS_OOP>::value &&
-    HasDecorator<decorators, INTERNAL_CONVERT_COMPRESSED_OOP>::value &&
-    HasDecorator<decorators, INTERNAL_RT_USE_COMPRESSED_OOPS>::value> {};
+    IsSame<typename HeapOopType<decorators>::type, narrowOop>::value &&
+    IsSame<T, oop>::value> {};
 
   // This metafunction returns an appropriate oop type if the value is oop-like
   // and otherwise returns the same type T.
@@ -172,13 +173,13 @@
   // Only encode if INTERNAL_VALUE_IS_OOP
   template <DecoratorSet idecorators, typename T>
   static inline typename EnableIf<
-    AccessInternal::MustConvertCompressedOop<idecorators>::value,
+    AccessInternal::MustConvertCompressedOop<idecorators, T>::value,
     typename HeapOopType<idecorators>::type>::type
   encode_internal(T value);
 
   template <DecoratorSet idecorators, typename T>
   static inline typename EnableIf<
-    !AccessInternal::MustConvertCompressedOop<idecorators>::value, T>::type
+    !AccessInternal::MustConvertCompressedOop<idecorators, T>::value, T>::type
   encode_internal(T value) {
     return value;
   }
@@ -192,12 +193,12 @@
   // Only decode if INTERNAL_VALUE_IS_OOP
   template <DecoratorSet idecorators, typename T>
   static inline typename EnableIf<
-    AccessInternal::MustConvertCompressedOop<idecorators>::value, T>::type
+    AccessInternal::MustConvertCompressedOop<idecorators, T>::value, T>::type
   decode_internal(typename HeapOopType<idecorators>::type value);
 
   template <DecoratorSet idecorators, typename T>
   static inline typename EnableIf<
-    !AccessInternal::MustConvertCompressedOop<idecorators>::value, T>::type
+    !AccessInternal::MustConvertCompressedOop<idecorators, T>::value, T>::type
   decode_internal(T value) {
     return value;
   }
--- a/src/hotspot/share/oops/accessBackend.inline.hpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/oops/accessBackend.inline.hpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2017, 2018, 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
@@ -32,7 +32,7 @@
 template <DecoratorSet decorators>
 template <DecoratorSet idecorators, typename T>
 inline typename EnableIf<
-  AccessInternal::MustConvertCompressedOop<idecorators>::value, T>::type
+  AccessInternal::MustConvertCompressedOop<idecorators, T>::value, T>::type
 RawAccessBarrier<decorators>::decode_internal(typename HeapOopType<idecorators>::type value) {
   if (HasDecorator<decorators, OOP_NOT_NULL>::value) {
     return oopDesc::decode_heap_oop_not_null(value);
@@ -44,7 +44,7 @@
 template <DecoratorSet decorators>
 template <DecoratorSet idecorators, typename T>
 inline typename EnableIf<
-  AccessInternal::MustConvertCompressedOop<idecorators>::value,
+  AccessInternal::MustConvertCompressedOop<idecorators, T>::value,
   typename HeapOopType<idecorators>::type>::type
 RawAccessBarrier<decorators>::encode_internal(T value) {
   if (HasDecorator<decorators, OOP_NOT_NULL>::value) {
--- a/src/hotspot/share/oops/compiledICHolder.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/oops/compiledICHolder.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -32,8 +32,8 @@
 volatile int CompiledICHolder::_live_not_claimed_count;
 
 
-CompiledICHolder::CompiledICHolder(Method* method, Klass* klass)
-  : _holder_method(method), _holder_klass(klass) {
+CompiledICHolder::CompiledICHolder(Metadata* metadata, Klass* klass)
+  : _holder_metadata(metadata), _holder_klass(klass) {
 #ifdef ASSERT
   Atomic::inc(&_live_count);
   Atomic::inc(&_live_not_claimed_count);
@@ -47,12 +47,28 @@
 }
 #endif // ASSERT
 
+bool CompiledICHolder::is_loader_alive(BoolObjectClosure* is_alive) {
+  if (_holder_metadata->is_method()) {
+    if (!((Method*)_holder_metadata)->method_holder()->is_loader_alive(is_alive)) {
+      return false;
+    }
+  } else if (_holder_metadata->is_klass()) {
+    if (!((Klass*)_holder_metadata)->is_loader_alive(is_alive)) {
+      return false;
+    }
+  }
+  if (!_holder_klass->is_loader_alive(is_alive)) {
+    return false;
+  }
+  return true;
+}
+
 // Printing
 
 void CompiledICHolder::print_on(outputStream* st) const {
   st->print("%s", internal_name());
-  st->print(" - method: "); holder_method()->print_value_on(st); st->cr();
-  st->print(" - klass:  "); holder_klass()->print_value_on(st); st->cr();
+  st->print(" - metadata: "); holder_metadata()->print_value_on(st); st->cr();
+  st->print(" - klass:    "); holder_klass()->print_value_on(st); st->cr();
 }
 
 void CompiledICHolder::print_value_on(outputStream* st) const {
@@ -63,7 +79,7 @@
 // Verification
 
 void CompiledICHolder::verify_on(outputStream* st) {
-  guarantee(holder_method()->is_method(), "should be method");
+  guarantee(holder_metadata()->is_method() || holder_metadata()->is_klass(), "should be method or klass");
   guarantee(holder_klass()->is_klass(),   "should be klass");
 }
 
--- a/src/hotspot/share/oops/compiledICHolder.hpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/oops/compiledICHolder.hpp	Fri Jan 19 09:32:10 2018 -0800
@@ -29,8 +29,9 @@
 #include "utilities/macros.hpp"
 
 // A CompiledICHolder* is a helper object for the inline cache implementation.
-// It holds an intermediate value (method+klass pair) used when converting from
-// compiled to an interpreted call.
+// It holds:
+//   (1) (method+klass pair) when converting from compiled to an interpreted call
+//   (2) (klass+klass pair) when calling itable stub from megamorphic compiled call
 //
 // These are always allocated in the C heap and are freed during a
 // safepoint by the ICBuffer logic.  It's unsafe to free them earlier
@@ -45,32 +46,33 @@
   static volatile int _live_not_claimed_count; // allocated but not yet in use so not
                                                // reachable by iterating over nmethods
 
-  Method* _holder_method;
+  Metadata* _holder_metadata;
   Klass*    _holder_klass;    // to avoid name conflict with oopDesc::_klass
   CompiledICHolder* _next;
 
  public:
   // Constructor
-  CompiledICHolder(Method* method, Klass* klass);
+  CompiledICHolder(Metadata* metadata, Klass* klass);
   ~CompiledICHolder() NOT_DEBUG_RETURN;
 
   static int live_count() { return _live_count; }
   static int live_not_claimed_count() { return _live_not_claimed_count; }
 
   // accessors
-  Method* holder_method() const     { return _holder_method; }
   Klass*    holder_klass()  const     { return _holder_klass; }
+  Metadata* holder_metadata() const   { return _holder_metadata; }
 
-  void set_holder_method(Method* m) { _holder_method = m; }
-  void set_holder_klass(Klass* k)   { _holder_klass = k; }
+  void set_holder_metadata(Metadata* m) { _holder_metadata = m; }
+  void set_holder_klass(Klass* k)     { _holder_klass = k; }
 
-  // interpreter support (offsets in bytes)
-  static int holder_method_offset()   { return offset_of(CompiledICHolder, _holder_method); }
+  static int holder_metadata_offset() { return offset_of(CompiledICHolder, _holder_metadata); }
   static int holder_klass_offset()    { return offset_of(CompiledICHolder, _holder_klass); }
 
   CompiledICHolder* next()     { return _next; }
   void set_next(CompiledICHolder* n) { _next = n; }
 
+  bool is_loader_alive(BoolObjectClosure* is_alive);
+
   // Verify
   void verify_on(outputStream* st);
 
--- a/src/hotspot/share/oops/constantPool.hpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/oops/constantPool.hpp	Fri Jan 19 09:32:10 2018 -0800
@@ -25,6 +25,7 @@
 #ifndef SHARE_VM_OOPS_CONSTANTPOOLOOP_HPP
 #define SHARE_VM_OOPS_CONSTANTPOOLOOP_HPP
 
+#include "memory/allocation.inline.hpp"
 #include "oops/arrayOop.hpp"
 #include "oops/cpCache.hpp"
 #include "oops/objArrayOop.hpp"
@@ -1021,7 +1022,7 @@
         delete(cur);
       }
     }
-    delete _buckets;
+    FREE_C_HEAP_ARRAY(SymbolHashMapBucket, _buckets);
   }
 }; // End SymbolHashMap class
 
--- a/src/hotspot/share/oops/cpCache.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/oops/cpCache.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -278,14 +278,16 @@
   set_direct_or_vtable_call(invoke_code, method, index, false);
 }
 
-void ConstantPoolCacheEntry::set_itable_call(Bytecodes::Code invoke_code, const methodHandle& method, int index) {
+void ConstantPoolCacheEntry::set_itable_call(Bytecodes::Code invoke_code,
+                                             Klass* referenced_klass,
+                                             const methodHandle& method, int index) {
   assert(method->method_holder()->verify_itable_index(index), "");
   assert(invoke_code == Bytecodes::_invokeinterface, "");
   InstanceKlass* interf = method->method_holder();
   assert(interf->is_interface(), "must be an interface");
   assert(!method->is_final_method(), "interfaces do not have final methods; cannot link to one here");
-  set_f1(interf);
-  set_f2(index);
+  set_f1(referenced_klass);
+  set_f2((intx)method());
   set_method_flags(as_TosState(method->result_type()),
                    0,  // no option bits
                    method()->size_of_parameters());
@@ -514,10 +516,23 @@
 
 
 #if INCLUDE_JVMTI
+
+void log_adjust(const char* entry_type, Method* old_method, Method* new_method, bool* trace_name_printed) {
+  if (log_is_enabled(Info, redefine, class, update)) {
+    ResourceMark rm;
+    if (!(*trace_name_printed)) {
+      log_info(redefine, class, update)("adjust: name=%s", old_method->method_holder()->external_name());
+      *trace_name_printed = true;
+    }
+    log_debug(redefine, class, update, constantpool)
+          ("cpc %s entry update: %s(%s)", entry_type, new_method->name()->as_C_string(), new_method->signature()->as_C_string());
+  }
+}
+
 // RedefineClasses() API support:
 // If this ConstantPoolCacheEntry refers to old_method then update it
 // to refer to new_method.
-bool ConstantPoolCacheEntry::adjust_method_entry(Method* old_method,
+void ConstantPoolCacheEntry::adjust_method_entry(Method* old_method,
        Method* new_method, bool * trace_name_printed) {
 
   if (is_vfinal()) {
@@ -526,63 +541,35 @@
       // match old_method so need an update
       // NOTE: can't use set_f2_as_vfinal_method as it asserts on different values
       _f2 = (intptr_t)new_method;
-      if (log_is_enabled(Info, redefine, class, update)) {
-        ResourceMark rm;
-        if (!(*trace_name_printed)) {
-          log_info(redefine, class, update)("adjust: name=%s", old_method->method_holder()->external_name());
-          *trace_name_printed = true;
-        }
-        log_debug(redefine, class, update, constantpool)
-          ("cpc vf-entry update: %s(%s)", new_method->name()->as_C_string(), new_method->signature()->as_C_string());
-      }
-      return true;
+      log_adjust("vfinal", old_method, new_method, trace_name_printed);
     }
-
-    // f1() is not used with virtual entries so bail out
-    return false;
+    return;
   }
 
-  if (_f1 == NULL) {
-    // NULL f1() means this is a virtual entry so bail out
-    // We are assuming that the vtable index does not need change.
-    return false;
-  }
+  assert (_f1 != NULL, "should not call with uninteresting entry");
 
-  if (_f1 == old_method) {
+  if (!(_f1->is_method())) {
+    // _f1 is a Klass* for an interface, _f2 is the method
+    if (f2_as_interface_method() == old_method) {
+      _f2 = (intptr_t)new_method;
+      log_adjust("interface", old_method, new_method, trace_name_printed);
+    }
+  } else if (_f1 == old_method) {
     _f1 = new_method;
-    if (log_is_enabled(Info, redefine, class, update)) {
-      ResourceMark rm;
-      if (!(*trace_name_printed)) {
-        log_info(redefine, class, update)("adjust: name=%s", old_method->method_holder()->external_name());
-        *trace_name_printed = true;
-      }
-      log_debug(redefine, class, update, constantpool)
-        ("cpc entry update: %s(%s)", new_method->name()->as_C_string(), new_method->signature()->as_C_string());
-    }
-    return true;
+    log_adjust("special, static or dynamic", old_method, new_method, trace_name_printed);
   }
-
-  return false;
 }
 
 // a constant pool cache entry should never contain old or obsolete methods
 bool ConstantPoolCacheEntry::check_no_old_or_obsolete_entries() {
-  if (is_vfinal()) {
-    // virtual and final so _f2 contains method ptr instead of vtable index
-    Metadata* f2 = (Metadata*)_f2;
-    // Return false if _f2 refers to an old or an obsolete method.
-    // _f2 == NULL || !_f2->is_method() are just as unexpected here.
-    return (f2 != NULL NOT_PRODUCT(&& f2->is_valid()) && f2->is_method() &&
-            !((Method*)f2)->is_old() && !((Method*)f2)->is_obsolete());
-  } else if (_f1 == NULL ||
-             (NOT_PRODUCT(_f1->is_valid() &&) !_f1->is_method())) {
-    // _f1 == NULL || !_f1->is_method() are OK here
+  Method* m = get_interesting_method_entry(NULL);
+  // return false if m refers to a non-deleted old or obsolete method
+  if (m != NULL) {
+    assert(m->is_valid() && m->is_method(), "m is a valid method");
+    return !m->is_old() && !m->is_obsolete(); // old is always set for old and obsolete
+  } else {
     return true;
   }
-  // return false if _f1 refers to a non-deleted old or obsolete method
-  return (NOT_PRODUCT(_f1->is_valid() &&) _f1->is_method() &&
-          (f1_as_method()->is_deleted() ||
-          (!f1_as_method()->is_old() && !f1_as_method()->is_obsolete())));
 }
 
 Method* ConstantPoolCacheEntry::get_interesting_method_entry(Klass* k) {
@@ -599,10 +586,11 @@
     return NULL;
   } else {
     if (!(_f1->is_method())) {
-      // _f1 can also contain a Klass* for an interface
-      return NULL;
+      // _f1 is a Klass* for an interface
+      m = f2_as_interface_method();
+    } else {
+      m = f1_as_method();
     }
-    m = f1_as_method();
   }
   assert(m != NULL && m->is_method(), "sanity check");
   if (m == NULL || !m->is_method() || (k != NULL && m->method_holder() != k)) {
--- a/src/hotspot/share/oops/cpCache.hpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/oops/cpCache.hpp	Fri Jan 19 09:32:10 2018 -0800
@@ -249,6 +249,7 @@
 
   void set_itable_call(
     Bytecodes::Code invoke_code,                 // the bytecode used; must be invokeinterface
+    Klass* referenced_klass,                     // the referenced klass in the InterfaceMethodref
     const methodHandle& method,                  // the resolved interface method
     int itable_index                             // index into itable for the method
   );
@@ -352,6 +353,7 @@
   bool      is_f1_null() const                   { Metadata* f1 = f1_ord(); return f1 == NULL; }  // classifies a CPC entry as unbound
   int       f2_as_index() const                  { assert(!is_vfinal(), ""); return (int) _f2; }
   Method*   f2_as_vfinal_method() const          { assert(is_vfinal(), ""); return (Method*)_f2; }
+  Method*   f2_as_interface_method() const       { assert(bytecode_1() == Bytecodes::_invokeinterface, ""); return (Method*)_f2; }
   intx flags_ord() const                         { return (intx)OrderAccess::load_acquire(&_flags); }
   int  field_index() const                       { assert(is_field_entry(),  ""); return (_flags & field_index_mask); }
   int  parameter_size() const                    { assert(is_method_entry(), ""); return (_flags & parameter_size_mask); }
@@ -387,7 +389,7 @@
   // trace_name_printed is set to true if the current call has
   // printed the klass name so that other routines in the adjust_*
   // group don't print the klass name.
-  bool adjust_method_entry(Method* old_method, Method* new_method,
+  void adjust_method_entry(Method* old_method, Method* new_method,
          bool* trace_name_printed);
   bool check_no_old_or_obsolete_entries();
   Method* get_interesting_method_entry(Klass* k);
--- a/src/hotspot/share/oops/instanceKlass.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/oops/instanceKlass.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, 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
@@ -2265,7 +2265,8 @@
 }
 
 address InstanceKlass::static_field_addr(int offset) {
-  return (address)(offset + InstanceMirrorKlass::offset_of_static_fields() + cast_from_oop<intptr_t>(java_mirror()));
+  assert(offset >= InstanceMirrorKlass::offset_of_static_fields(), "has already been adjusted");
+  return (address)(offset + cast_from_oop<intptr_t>(java_mirror()));
 }
 
 
@@ -3421,6 +3422,15 @@
   }
 }
 
+oop InstanceKlass::klass_holder_phantom() {
+  oop* addr;
+  if (is_anonymous()) {
+    addr = _java_mirror.ptr_raw();
+  } else {
+    addr = &class_loader_data()->_class_loader;
+  }
+  return RootAccess<IN_CONCURRENT_ROOT | ON_PHANTOM_OOP_REF>::oop_load(addr);
+}
 
 #ifdef ASSERT
 void InstanceKlass::set_init_state(ClassState state) {
--- a/src/hotspot/share/oops/instanceKlass.hpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/oops/instanceKlass.hpp	Fri Jan 19 09:32:10 2018 -0800
@@ -609,9 +609,11 @@
   InstanceKlass* host_klass() const              {
     InstanceKlass** hk = adr_host_klass();
     if (hk == NULL) {
+      assert(!is_anonymous(), "Anonymous classes have host klasses");
       return NULL;
     } else {
       assert(*hk != NULL, "host klass should always be set if the address is not null");
+      assert(is_anonymous(), "Only anonymous classes have host klasses");
       return *hk;
     }
   }
@@ -623,6 +625,9 @@
       *addr = host;
     }
   }
+  bool has_host_klass() const              {
+    return adr_host_klass() != NULL;
+  }
   bool is_anonymous() const                {
     return (_misc_flags & _misc_is_anonymous) != 0;
   }
@@ -640,6 +645,11 @@
     return is_anonymous() ? java_mirror() : class_loader();
   }
 
+  // Load the klass_holder as a phantom. This is useful when a weak Klass
+  // pointer has been "peeked" and then must be kept alive before it may
+  // be used safely.
+  oop klass_holder_phantom();
+
   bool is_contended() const                {
     return (_misc_flags & _misc_is_contended) != 0;
   }
--- a/src/hotspot/share/oops/klassVtable.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/oops/klassVtable.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1200,7 +1200,6 @@
   Array<Method*>* methods = InstanceKlass::cast(interf)->methods();
   int nof_methods = methods->length();
   HandleMark hm;
-  assert(nof_methods > 0, "at least one method must exist for interface to be in vtable");
   Handle interface_loader (THREAD, InstanceKlass::cast(interf)->class_loader());
 
   int ime_count = method_count_for_interface(interf);
@@ -1369,8 +1368,10 @@
       }
     }
 
-    // Only count interfaces with at least one method
-    if (method_count > 0) {
+    // Visit all interfaces which either have any methods or can participate in receiver type check.
+    // We do not bother to count methods in transitive interfaces, although that would allow us to skip
+    // this step in the rare case of a zero-method interface extending another zero-method interface.
+    if (method_count > 0 || InstanceKlass::cast(intf)->transitive_interfaces()->length() > 0) {
       blk->doit(intf, method_count);
     }
   }
--- a/src/hotspot/share/oops/method.hpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/oops/method.hpp	Fri Jan 19 09:32:10 2018 -0800
@@ -698,6 +698,7 @@
   static ByteSize from_interpreted_offset()      { return byte_offset_of(Method, _from_interpreted_entry ); }
   static ByteSize interpreter_entry_offset()     { return byte_offset_of(Method, _i2i_entry ); }
   static ByteSize signature_handler_offset()     { return in_ByteSize(sizeof(Method) + wordSize);      }
+  static ByteSize itable_index_offset()          { return byte_offset_of(Method, _vtable_index ); }
 
   // for code generation
   static int method_data_offset_in_bytes()       { return offset_of(Method, _method_data); }
--- a/src/hotspot/share/oops/oop.hpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/oops/oop.hpp	Fri Jan 19 09:32:10 2018 -0800
@@ -28,6 +28,7 @@
 #include "gc/shared/specialized_oop_closures.hpp"
 #include "memory/iterator.hpp"
 #include "memory/memRegion.hpp"
+#include "oops/access.hpp"
 #include "oops/metadata.hpp"
 #include "utilities/macros.hpp"
 
@@ -178,6 +179,8 @@
   static inline void encode_store_heap_oop(oop* p, oop v);
 
   // Access to fields in a instanceOop through these methods.
+  template <DecoratorSet decorator>
+  oop obj_field_access(int offset) const;
   oop obj_field(int offset) const;
   void obj_field_put(int offset, oop value);
   void obj_field_put_raw(int offset, oop value);
--- a/src/hotspot/share/oops/oop.inline.hpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/oops/oop.inline.hpp	Fri Jan 19 09:32:10 2018 -0800
@@ -326,7 +326,10 @@
   *p = encode_heap_oop(v);
 }
 
+template <DecoratorSet decorators>
+inline oop  oopDesc::obj_field_access(int offset) const             { return HeapAccess<decorators>::oop_load_at(as_oop(), offset); }
 inline oop  oopDesc::obj_field(int offset) const                    { return HeapAccess<>::oop_load_at(as_oop(), offset);  }
+
 inline void oopDesc::obj_field_put(int offset, oop value)           { HeapAccess<>::oop_store_at(as_oop(), offset, value); }
 
 inline jbyte oopDesc::byte_field(int offset) const                  { return HeapAccess<>::load_at(as_oop(), offset);  }
--- a/src/hotspot/share/opto/callnode.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/opto/callnode.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, 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
@@ -772,7 +772,7 @@
     ciKlass* boxing_klass = t_oop->klass();
     if (is_CallStaticJava() && as_CallStaticJava()->is_boxing_method()) {
       // Skip unrelated boxing methods.
-      Node* proj = proj_out(TypeFunc::Parms);
+      Node* proj = proj_out_or_null(TypeFunc::Parms);
       if ((proj == NULL) || (phase->type(proj)->is_instptr()->klass() != boxing_klass)) {
         return false;
       }
@@ -784,7 +784,7 @@
       }
       // May modify (by reflection) if an boxing object is passed
       // as argument or returned.
-      Node* proj = returns_pointer() ? proj_out(TypeFunc::Parms) : NULL;
+      Node* proj = returns_pointer() ? proj_out_or_null(TypeFunc::Parms) : NULL;
       if (proj != NULL) {
         const TypeInstPtr* inst_t = phase->type(proj)->isa_instptr();
         if ((inst_t != NULL) && (!inst_t->klass_is_exact() ||
@@ -824,7 +824,7 @@
 Node *CallNode::result_cast() {
   Node *cast = NULL;
 
-  Node *p = proj_out(TypeFunc::Parms);
+  Node *p = proj_out_or_null(TypeFunc::Parms);
   if (p == NULL)
     return NULL;
 
@@ -1378,13 +1378,13 @@
       PhaseIterGVN *igvn = phase->is_IterGVN();
       // Unreachable fall through path (negative array length),
       // the allocation can only throw so disconnect it.
-      Node* proj = proj_out(TypeFunc::Control);
+      Node* proj = proj_out_or_null(TypeFunc::Control);
       Node* catchproj = NULL;
       if (proj != NULL) {
         for (DUIterator_Fast imax, i = proj->fast_outs(imax); i < imax; i++) {
           Node *cn = proj->fast_out(i);
           if (cn->is_Catch()) {
-            catchproj = cn->as_Multi()->proj_out(CatchProjNode::fall_through_index);
+            catchproj = cn->as_Multi()->proj_out_or_null(CatchProjNode::fall_through_index);
             break;
           }
         }
@@ -1442,7 +1442,7 @@
       // Create a cast which is control dependent on the initialization to
       // propagate the fact that the array length must be positive.
       length = new CastIINode(length, narrow_length_type);
-      length->set_req(0, initialization()->proj_out(0));
+      length->set_req(0, initialization()->proj_out_or_null(0));
     }
   }
 
--- a/src/hotspot/share/opto/cfgnode.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/opto/cfgnode.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, 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
@@ -2373,7 +2373,7 @@
   if (can_reshape && !in(0)->is_Loop()) {
     // Dead code elimination can sometimes delete this projection so
     // if it's not there, there's nothing to do.
-    Node* fallthru = proj_out(0);
+    Node* fallthru = proj_out_or_null(0);
     if (fallthru != NULL) {
       phase->is_IterGVN()->replace_node(fallthru, in(0));
     }
--- a/src/hotspot/share/opto/divnode.hpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/opto/divnode.hpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, 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
@@ -154,8 +154,8 @@
   virtual bool is_CFG() const  { return false; }
   virtual uint ideal_reg() const { return NotAMachineReg; }
 
-  ProjNode* div_proj() { return proj_out(div_proj_num); }
-  ProjNode* mod_proj() { return proj_out(mod_proj_num); }
+  ProjNode* div_proj() { return proj_out_or_null(div_proj_num); }
+  ProjNode* mod_proj() { return proj_out_or_null(mod_proj_num); }
 };
 
 //------------------------------DivModINode---------------------------------------
--- a/src/hotspot/share/opto/escape.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/opto/escape.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2018, 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
@@ -366,7 +366,7 @@
       delayed_worklist->push(n);
       // Check if a call returns an object.
       if ((n->as_Call()->returns_pointer() &&
-           n->as_Call()->proj_out(TypeFunc::Parms) != NULL) ||
+           n->as_Call()->proj_out_or_null(TypeFunc::Parms) != NULL) ||
           (n->is_CallStaticJava() &&
            n->as_CallStaticJava()->is_boxing_method())) {
         add_call_node(n->as_Call());
@@ -2674,7 +2674,7 @@
   PhaseGVN* igvn = _igvn;
   const TypeOopPtr *toop = C->get_adr_type(alias_idx)->isa_oopptr();
   bool is_instance = (toop != NULL) && toop->is_known_instance();
-  Node *start_mem = C->start()->proj_out(TypeFunc::Memory);
+  Node *start_mem = C->start()->proj_out_or_null(TypeFunc::Memory);
   Node *prev = NULL;
   Node *result = orig_mem;
   while (prev != result) {
@@ -3028,7 +3028,7 @@
         // An allocation may have an Initialize which has raw stores. Scan
         // the users of the raw allocation result and push AddP users
         // on alloc_worklist.
-        Node *raw_result = alloc->proj_out(TypeFunc::Parms);
+        Node *raw_result = alloc->proj_out_or_null(TypeFunc::Parms);
         assert (raw_result != NULL, "must have an allocation result");
         for (DUIterator_Fast imax, i = raw_result->fast_outs(imax); i < imax; i++) {
           Node *use = raw_result->fast_out(i);
@@ -3219,7 +3219,7 @@
       // we don't need to do anything, but the users must be pushed
     } else if (n->is_MemBar()) { // Initialize, MemBar nodes
       // we don't need to do anything, but the users must be pushed
-      n = n->as_MemBar()->proj_out(TypeFunc::Memory);
+      n = n->as_MemBar()->proj_out_or_null(TypeFunc::Memory);
       if (n == NULL)
         continue;
     } else if (n->Opcode() == Op_StrCompressedCopy ||
--- a/src/hotspot/share/opto/graphKit.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/opto/graphKit.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2018, 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
@@ -3754,7 +3754,7 @@
 
 // Trace Allocate -> Proj[Parm] -> Initialize
 InitializeNode* AllocateNode::initialization() {
-  ProjNode* rawoop = proj_out(AllocateNode::RawAddress);
+  ProjNode* rawoop = proj_out_or_null(AllocateNode::RawAddress);
   if (rawoop == NULL)  return NULL;
   for (DUIterator_Fast imax, i = rawoop->fast_outs(imax); i < imax; i++) {
     Node* init = rawoop->fast_out(i);
--- a/src/hotspot/share/opto/ifnode.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/opto/ifnode.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2018, 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
@@ -505,7 +505,7 @@
   //  Flip 1:  If (Bool[<] CmpU(l, LoadRange)) ...
   //  Flip 2:  If (Bool[<=] CmpU(LoadRange, l)) ...
 
-  ProjNode* iftrap = proj_out(flip_test == 2 ? true : false);
+  ProjNode* iftrap = proj_out_or_null(flip_test == 2 ? true : false);
   return iftrap;
 }
 
@@ -1195,14 +1195,17 @@
 // Check that the If that is in between the 2 integer comparisons has
 // no side effect
 bool IfNode::is_side_effect_free_test(ProjNode* proj, PhaseIterGVN* igvn) {
-  if (proj != NULL &&
-      proj->is_uncommon_trap_if_pattern(Deoptimization::Reason_none) &&
-      proj->outcnt() <= 2) {
+  if (proj == NULL) {
+    return false;
+  }
+  CallStaticJavaNode* unc = proj->is_uncommon_trap_if_pattern(Deoptimization::Reason_none);
+  if (unc != NULL && proj->outcnt() <= 2) {
     if (proj->outcnt() == 1 ||
         // Allow simple null check from LoadRange
         (is_cmp_with_loadrange(proj) && is_null_check(proj, igvn))) {
       CallStaticJavaNode* unc = proj->is_uncommon_trap_if_pattern(Deoptimization::Reason_none);
       CallStaticJavaNode* dom_unc = proj->in(0)->in(0)->as_Proj()->is_uncommon_trap_if_pattern(Deoptimization::Reason_none);
+      assert(dom_unc != NULL, "is_uncommon_trap_if_pattern returned NULL");
 
       // reroute_side_effect_free_unc changes the state of this
       // uncommon trap to restart execution at the previous
@@ -1471,7 +1474,7 @@
   // be skipped. For example, range check predicate has two checks
   // for lower and upper bounds.
   ProjNode* unc_proj = proj_out(1 - prev_dom->as_Proj()->_con)->as_Proj();
-  if ((unc_proj != NULL) && (unc_proj->is_uncommon_trap_proj(Deoptimization::Reason_predicate) != NULL)) {
+  if (unc_proj->is_uncommon_trap_proj(Deoptimization::Reason_predicate) != NULL) {
     prev_dom = idom;
   }
 
--- a/src/hotspot/share/opto/library_call.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/opto/library_call.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2018, 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
@@ -1495,7 +1495,7 @@
     // escape analysis can go from the MemBarStoreStoreNode to the
     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
     // based on the escape status of the AllocateNode.
-    insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out(AllocateNode::RawAddress));
+    insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
   }
   if (compress) {
     set_result(_gvn.transform(count));
@@ -1589,7 +1589,7 @@
       // escape analysis can go from the MemBarStoreStoreNode to the
       // AllocateNode and eliminate the MemBarStoreStoreNode if possible
       // based on the escape status of the AllocateNode.
-      insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out(AllocateNode::RawAddress));
+      insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
     } else {
       insert_mem_bar(Op_MemBarCPUOrder);
     }
@@ -1675,7 +1675,7 @@
       // escape analysis can go from the MemBarStoreStoreNode to the
       // AllocateNode and eliminate the MemBarStoreStoreNode if possible
       // based on the escape status of the AllocateNode.
-      insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out(AllocateNode::RawAddress));
+      insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
     } else {
       insert_mem_bar(Op_MemBarCPUOrder);
     }
@@ -4722,7 +4722,7 @@
     // escape analysis can go from the MemBarStoreStoreNode to the
     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
     // based on the escape status of the AllocateNode.
-    insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out(AllocateNode::RawAddress));
+    insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
   } else {
     insert_mem_bar(Op_MemBarCPUOrder);
   }
@@ -5031,7 +5031,7 @@
     Node *mem = reset_memory();
     set_all_memory(mem);
     alloc->set_req(TypeFunc::Memory, mem);
-    set_control(init->proj_out(TypeFunc::Control));
+    set_control(init->proj_out_or_null(TypeFunc::Control));
     set_i_o(callprojs.fallthrough_ioproj);
 
     // Update memory as done in GraphKit::set_output_for_allocation()
@@ -5042,8 +5042,8 @@
     }
     const TypePtr* telemref = ary_type->add_offset(Type::OffsetBot);
     int            elemidx  = C->get_alias_index(telemref);
-    set_memory(init->proj_out(TypeFunc::Memory), Compile::AliasIdxRaw);
-    set_memory(init->proj_out(TypeFunc::Memory), elemidx);
+    set_memory(init->proj_out_or_null(TypeFunc::Memory), Compile::AliasIdxRaw);
+    set_memory(init->proj_out_or_null(TypeFunc::Memory), elemidx);
 
     Node* allocx = _gvn.transform(alloc);
     assert(allocx == alloc, "where has the allocation gone?");
@@ -5360,7 +5360,7 @@
     // to finish initializing the allocated object.
     if ((ctl->is_IfFalse() || ctl->is_IfTrue()) && ctl->in(0)->is_If()) {
       IfNode* iff = ctl->in(0)->as_If();
-      Node* not_ctl = iff->proj_out(1 - ctl->as_Proj()->_con);
+      Node* not_ctl = iff->proj_out_or_null(1 - ctl->as_Proj()->_con);
       assert(not_ctl != NULL && not_ctl != ctl, "found alternate");
       if (slow_region != NULL && slow_region->find_edge(not_ctl) >= 1) {
         ctl = iff->in(0);       // This test feeds the known slow_region.
--- a/src/hotspot/share/opto/loopTransform.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/opto/loopTransform.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2018, 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
@@ -1017,7 +1017,6 @@
   CountedLoopNode *main_head = loop->_head->as_CountedLoop();
   assert( main_head->is_normal_loop(), "" );
   CountedLoopEndNode *main_end = main_head->loopexit();
-  guarantee(main_end != NULL, "no loop exit node");
   assert( main_end->outcnt() == 2, "1 true, 1 false path only" );
 
   Node *pre_header= main_head->in(LoopNode::EntryControl);
@@ -1243,7 +1242,6 @@
   // Find common pieces of the loop being guarded with pre & post loops
   CountedLoopNode *main_head = loop->_head->as_CountedLoop();
   CountedLoopEndNode *main_end = main_head->loopexit();
-  guarantee(main_end != NULL, "no loop exit node");
   // diagnostic to show loop end is not properly formed
   assert(main_end->outcnt() == 2, "1 true, 1 false path only");
 
@@ -1293,7 +1291,6 @@
   // Find common pieces of the loop being guarded with pre & post loops
   CountedLoopNode *main_head = loop->_head->as_CountedLoop();
   CountedLoopEndNode *main_end = main_head->loopexit();
-  guarantee(main_end != NULL, "no loop exit node");
   // diagnostic to show loop end is not properly formed
   assert(main_end->outcnt() == 2, "1 true, 1 false path only");
 
@@ -1427,7 +1424,6 @@
   assert(LoopUnrollLimit, "");
   CountedLoopNode *loop_head = loop->_head->as_CountedLoop();
   CountedLoopEndNode *loop_end = loop_head->loopexit();
-  assert(loop_end, "");
 #ifndef PRODUCT
   if (PrintOpto && VerifyLoopOptimizations) {
     tty->print("Unrolling ");
@@ -2972,7 +2968,7 @@
       }
       store = n;
       store_value = value;
-    } else if (n->is_If() && n != head->loopexit()) {
+    } else if (n->is_If() && n != head->loopexit_or_null()) {
       msg = "extra control flow";
       msg_node = n;
     }
@@ -3114,7 +3110,6 @@
   ok.set(store->in(MemNode::Memory)->_idx);
 
   CountedLoopEndNode* loop_exit = head->loopexit();
-  guarantee(loop_exit != NULL, "no loop exit node");
 
   // Loop structure is ok
   ok.set(head->_idx);
@@ -3204,7 +3199,7 @@
     return false;
   }
 
-  Node* exit = head->loopexit()->proj_out(0);
+  Node* exit = head->loopexit()->proj_out_or_null(0);
   if (exit == NULL) {
     return false;
   }
@@ -3280,8 +3275,8 @@
   call->init_req(TypeFunc::Control,   head->init_control());
   call->init_req(TypeFunc::I_O,       C->top());       // Does no I/O.
   call->init_req(TypeFunc::Memory,    mem_phi->in(LoopNode::EntryControl));
-  call->init_req(TypeFunc::ReturnAdr, C->start()->proj_out(TypeFunc::ReturnAdr));
-  call->init_req(TypeFunc::FramePtr,  C->start()->proj_out(TypeFunc::FramePtr));
+  call->init_req(TypeFunc::ReturnAdr, C->start()->proj_out_or_null(TypeFunc::ReturnAdr));
+  call->init_req(TypeFunc::FramePtr,  C->start()->proj_out_or_null(TypeFunc::FramePtr));
   _igvn.register_new_node_with_optimizer(call);
   result_ctrl = new ProjNode(call,TypeFunc::Control);
   _igvn.register_new_node_with_optimizer(result_ctrl);
--- a/src/hotspot/share/opto/loopnode.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/opto/loopnode.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2018, 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,11 +68,11 @@
 bool LoopNode::is_valid_counted_loop() const {
   if (is_CountedLoop()) {
     CountedLoopNode*    l  = as_CountedLoop();
-    CountedLoopEndNode* le = l->loopexit();
+    CountedLoopEndNode* le = l->loopexit_or_null();
     if (le != NULL &&
-        le->proj_out(1 /* true */) == l->in(LoopNode::LoopBackControl)) {
+        le->proj_out_or_null(1 /* true */) == l->in(LoopNode::LoopBackControl)) {
       Node* phi  = l->phi();
-      Node* exit = le->proj_out(0 /* false */);
+      Node* exit = le->proj_out_or_null(0 /* false */);
       if (exit != NULL && exit->Opcode() == Op_IfFalse &&
           phi != NULL && phi->is_Phi() &&
           phi->in(LoopNode::LoopBackControl) == l->incr() &&
@@ -793,7 +793,7 @@
 
 #ifdef ASSERT
   assert(l->is_valid_counted_loop(), "counted loop shape is messed up");
-  assert(l == loop->_head && l->phi() == phi && l->loopexit() == lex, "" );
+  assert(l == loop->_head && l->phi() == phi && l->loopexit_or_null() == lex, "" );
 #endif
 #ifndef PRODUCT
   if (TraceLoopOpts) {
@@ -917,7 +917,7 @@
       }
     }
     CountedLoopEndNode* cle = inner_out->in(0)->as_CountedLoopEnd();
-    assert(cle == inner->loopexit(), "mismatch");
+    assert(cle == inner->loopexit_or_null(), "mismatch");
     bool has_skeleton = outer_le->in(1)->bottom_type()->singleton() && outer_le->in(1)->bottom_type()->is_int()->get_con() == 0;
     if (has_skeleton) {
       assert(expect_skeleton == 1 || expect_skeleton == -1, "unexpected skeleton node");
@@ -1216,7 +1216,7 @@
   if (le == NULL) {
     return NULL;
   }
-  Node* c = le->proj_out(false);
+  Node* c = le->proj_out_or_null(false);
   if (c == NULL) {
     return NULL;
   }
--- a/src/hotspot/share/opto/loopnode.hpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/opto/loopnode.hpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2018, 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
@@ -215,6 +215,7 @@
 
   Node *init_control() const { return in(EntryControl); }
   Node *back_control() const { return in(LoopBackControl); }
+  CountedLoopEndNode *loopexit_or_null() const;
   CountedLoopEndNode *loopexit() const;
   Node *init_trip() const;
   Node *stride() const;
@@ -342,7 +343,7 @@
       return NULL;
     }
     Node *ln = iv_phi->in(0);
-    if (ln->is_CountedLoop() && ln->as_CountedLoop()->loopexit() == this) {
+    if (ln->is_CountedLoop() && ln->as_CountedLoop()->loopexit_or_null() == this) {
       return (CountedLoopNode*)ln;
     }
     return NULL;
@@ -354,7 +355,7 @@
 };
 
 
-inline CountedLoopEndNode *CountedLoopNode::loopexit() const {
+inline CountedLoopEndNode *CountedLoopNode::loopexit_or_null() const {
   Node *bc = back_control();
   if( bc == NULL ) return NULL;
   Node *le = bc->in(0);
@@ -362,13 +363,18 @@
     return NULL;
   return (CountedLoopEndNode*)le;
 }
-inline Node *CountedLoopNode::init_trip() const { return loopexit() ? loopexit()->init_trip() : NULL; }
-inline Node *CountedLoopNode::stride() const { return loopexit() ? loopexit()->stride() : NULL; }
-inline int CountedLoopNode::stride_con() const { return loopexit() ? loopexit()->stride_con() : 0; }
-inline bool CountedLoopNode::stride_is_con() const { return loopexit() && loopexit()->stride_is_con(); }
-inline Node *CountedLoopNode::limit() const { return loopexit() ? loopexit()->limit() : NULL; }
-inline Node *CountedLoopNode::incr() const { return loopexit() ? loopexit()->incr() : NULL; }
-inline Node *CountedLoopNode::phi() const { return loopexit() ? loopexit()->phi() : NULL; }
+inline CountedLoopEndNode *CountedLoopNode::loopexit() const {
+  CountedLoopEndNode* cle = loopexit_or_null();
+  assert(cle != NULL, "loopexit is NULL");
+  return cle;
+}
+inline Node *CountedLoopNode::init_trip() const { return loopexit_or_null() ? loopexit()->init_trip() : NULL; }
+inline Node *CountedLoopNode::stride() const { return loopexit_or_null() ? loopexit()->stride() : NULL; }
+inline int CountedLoopNode::stride_con() const { return loopexit_or_null() ? loopexit()->stride_con() : 0; }
+inline bool CountedLoopNode::stride_is_con() const { return loopexit_or_null() && loopexit()->stride_is_con(); }
+inline Node *CountedLoopNode::limit() const { return loopexit_or_null() ? loopexit()->limit() : NULL; }
+inline Node *CountedLoopNode::incr() const { return loopexit_or_null() ? loopexit()->incr() : NULL; }
+inline Node *CountedLoopNode::phi() const { return loopexit_or_null() ? loopexit()->phi() : NULL; }
 
 //------------------------------LoopLimitNode-----------------------------
 // Counted Loop limit node which represents exact final iterator value:
--- a/src/hotspot/share/opto/loopopts.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/opto/loopopts.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2018, 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
@@ -239,7 +239,7 @@
   // Make control-dependent data Nodes on the live path (path that will remain
   // once the dominated IF is removed) become control-dependent on the
   // dominating projection.
-  Node* dp = iff->as_If()->proj_out(pop == Op_IfTrue);
+  Node* dp = iff->as_If()->proj_out_or_null(pop == Op_IfTrue);
 
   // Loop predicates may have depending checks which should not
   // be skipped. For example, range check predicate has two checks
@@ -1731,7 +1731,7 @@
     Node* sfpt = cl->outer_safepoint();
     CountedLoopEndNode* cle = cl->loopexit();
     CountedLoopNode* new_cl = old_new[cl->_idx]->as_CountedLoop();
-    CountedLoopEndNode* new_cle = new_cl->as_CountedLoop()->loopexit();
+    CountedLoopEndNode* new_cle = new_cl->as_CountedLoop()->loopexit_or_null();
     Node* cle_out = cle->proj_out(false);
 
     Node* new_sfpt = NULL;
@@ -1956,7 +1956,7 @@
         if (head->is_strip_mined() && mode != IgnoreStripMined) {
           CountedLoopNode* cl = head->as_CountedLoop();
           CountedLoopEndNode* cle = cl->loopexit();
-          Node* cle_out = cle->proj_out(false);
+          Node* cle_out = cle->proj_out_or_null(false);
           if (use == cle_out) {
             IfNode* le = cl->outer_loop_end();
             use = le->proj_out(false);
--- a/src/hotspot/share/opto/macro.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/opto/macro.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2018, 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
@@ -496,7 +496,7 @@
   if (level <= 0) {
     return NULL; // Give up: phi tree too deep
   }
-  Node *start_mem = C->start()->proj_out(TypeFunc::Memory);
+  Node *start_mem = C->start()->proj_out_or_null(TypeFunc::Memory);
   Node *alloc_mem = alloc->in(TypeFunc::Memory);
 
   uint length = mem->req();
@@ -576,7 +576,7 @@
 
   int alias_idx = C->get_alias_index(adr_t);
   int offset = adr_t->offset();
-  Node *start_mem = C->start()->proj_out(TypeFunc::Memory);
+  Node *start_mem = C->start()->proj_out_or_null(TypeFunc::Memory);
   Node *alloc_ctrl = alloc->in(TypeFunc::Control);
   Node *alloc_mem = alloc->in(TypeFunc::Memory);
   Arena *a = Thread::current()->resource_area();
@@ -974,8 +974,8 @@
 }
 
 static void disconnect_projections(MultiNode* n, PhaseIterGVN& igvn) {
-  Node* ctl_proj = n->proj_out(TypeFunc::Control);
-  Node* mem_proj = n->proj_out(TypeFunc::Memory);
+  Node* ctl_proj = n->proj_out_or_null(TypeFunc::Control);
+  Node* mem_proj = n->proj_out_or_null(TypeFunc::Memory);
   if (ctl_proj != NULL) {
     igvn.replace_node(ctl_proj, n->in(0));
   }
@@ -1086,12 +1086,12 @@
         // Eliminate Initialize node.
         InitializeNode *init = use->as_Initialize();
         assert(init->outcnt() <= 2, "only a control and memory projection expected");
-        Node *ctrl_proj = init->proj_out(TypeFunc::Control);
+        Node *ctrl_proj = init->proj_out_or_null(TypeFunc::Control);
         if (ctrl_proj != NULL) {
            assert(init->in(TypeFunc::Control) == _fallthroughcatchproj, "allocation control projection");
           _igvn.replace_node(ctrl_proj, _fallthroughcatchproj);
         }
-        Node *mem_proj = init->proj_out(TypeFunc::Memory);
+        Node *mem_proj = init->proj_out_or_null(TypeFunc::Memory);
         if (mem_proj != NULL) {
           Node *mem = init->in(TypeFunc::Memory);
 #ifdef ASSERT
@@ -1198,7 +1198,7 @@
 
 bool PhaseMacroExpand::eliminate_boxing_node(CallStaticJavaNode *boxing) {
   // EA should remove all uses of non-escaping boxing node.
-  if (!C->eliminate_boxing() || boxing->proj_out(TypeFunc::Parms) != NULL) {
+  if (!C->eliminate_boxing() || boxing->proj_out_or_null(TypeFunc::Parms) != NULL) {
     return false;
   }
 
@@ -1580,8 +1580,8 @@
         // before the InitializeNode happen before the storestore
         // barrier.
 
-        Node* init_ctrl = init->proj_out(TypeFunc::Control);
-        Node* init_mem = init->proj_out(TypeFunc::Memory);
+        Node* init_ctrl = init->proj_out_or_null(TypeFunc::Control);
+        Node* init_mem = init->proj_out_or_null(TypeFunc::Memory);
 
         MemBarNode* mb = MemBarNode::make(C, Op_MemBarStoreStore, Compile::AliasIdxBot);
         transform_later(mb);
--- a/src/hotspot/share/opto/memnode.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/opto/memnode.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, 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
@@ -136,7 +136,7 @@
   if (!(is_instance || is_boxed_value_load))
     return mchain;  // don't try to optimize non-instance types
   uint instance_id = t_oop->instance_id();
-  Node *start_mem = phase->C->start()->proj_out(TypeFunc::Memory);
+  Node *start_mem = phase->C->start()->proj_out_or_null(TypeFunc::Memory);
   Node *prev = NULL;
   Node *result = mchain;
   while (prev != result) {
--- a/src/hotspot/share/opto/multnode.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/opto/multnode.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, 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
@@ -43,8 +43,8 @@
 Node *MultiNode::match( const ProjNode *proj, const Matcher *m ) { return proj->clone(); }
 
 //------------------------------proj_out---------------------------------------
-// Get a named projection
-ProjNode* MultiNode::proj_out(uint which_proj) const {
+// Get a named projection or null if not found
+ProjNode* MultiNode::proj_out_or_null(uint which_proj) const {
   assert((Opcode() != Op_If && Opcode() != Op_RangeCheck) || which_proj == (uint)true || which_proj == (uint)false, "must be 1 or 0");
   assert((Opcode() != Op_If && Opcode() != Op_RangeCheck) || outcnt() == 2, "bad if #1");
   for( DUIterator_Fast imax, i = fast_outs(imax); i < imax; i++ ) {
@@ -63,6 +63,13 @@
   return NULL;
 }
 
+// Get a named projection
+ProjNode* MultiNode::proj_out(uint which_proj) const {
+  ProjNode* p = proj_out_or_null(which_proj);
+  assert(p != NULL, "named projection %u not found", which_proj);
+  return p;
+}
+
 //=============================================================================
 //------------------------------ProjNode---------------------------------------
 uint ProjNode::hash() const {
@@ -214,8 +221,6 @@
   }
 
   ProjNode* other_proj = iff->proj_out(1-_con);
-  if (other_proj == NULL) // Should never happen, but make Parfait happy.
-      return NULL;
   CallStaticJavaNode* call = other_proj->is_uncommon_trap_proj(reason);
   if (call != NULL) {
     assert(reason == Deoptimization::Reason_none ||
--- a/src/hotspot/share/opto/multnode.hpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/opto/multnode.hpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, 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
@@ -47,6 +47,7 @@
   virtual Node *match( const ProjNode *proj, const Matcher *m );
   virtual uint ideal_reg() const { return NotAMachineReg; }
   ProjNode* proj_out(uint which_proj) const; // Get a named projection
+  ProjNode* proj_out_or_null(uint which_proj) const;
 
 };
 
--- a/src/hotspot/share/opto/phaseX.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/opto/phaseX.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, 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
@@ -1524,7 +1524,7 @@
     // receiver to know when to enable the regular fall-through path
     // in addition to the NullPtrException path.
     if (use->is_CallDynamicJava() && n == use->in(TypeFunc::Parms)) {
-      Node* p = use->as_CallDynamicJava()->proj_out(TypeFunc::Control);
+      Node* p = use->as_CallDynamicJava()->proj_out_or_null(TypeFunc::Control);
       if (p != NULL) {
         add_users_to_worklist0(p);
       }
@@ -1617,12 +1617,12 @@
     if (use_op == Op_Allocate || use_op == Op_AllocateArray) {
       InitializeNode* init = use->as_Allocate()->initialization();
       if (init != NULL) {
-        Node* imem = init->proj_out(TypeFunc::Memory);
+        Node* imem = init->proj_out_or_null(TypeFunc::Memory);
         if (imem != NULL)  add_users_to_worklist0(imem);
       }
     }
     if (use_op == Op_Initialize) {
-      Node* imem = use->as_Initialize()->proj_out(TypeFunc::Memory);
+      Node* imem = use->as_Initialize()->proj_out_or_null(TypeFunc::Memory);
       if (imem != NULL)  add_users_to_worklist0(imem);
     }
     // Loading the java mirror from a klass oop requires two loads and the type
--- a/src/hotspot/share/opto/stringopts.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/opto/stringopts.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2009, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2009, 2018, 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
@@ -362,11 +362,11 @@
   // Eliminate Initialize node.
   assert(init->outcnt() <= 2, "only a control and memory projection expected");
   assert(init->req() <= InitializeNode::RawStores, "no pending inits");
-  Node *ctrl_proj = init->proj_out(TypeFunc::Control);
+  Node *ctrl_proj = init->proj_out_or_null(TypeFunc::Control);
   if (ctrl_proj != NULL) {
     C->gvn_replace_by(ctrl_proj, init->in(TypeFunc::Control));
   }
-  Node *mem_proj = init->proj_out(TypeFunc::Memory);
+  Node *mem_proj = init->proj_out_or_null(TypeFunc::Memory);
   if (mem_proj != NULL) {
     Node *mem = init->in(TypeFunc::Memory);
     C->gvn_replace_by(mem_proj, mem);
@@ -891,7 +891,7 @@
       ctrl_path.push(cn);
       ctrl_path.push(cn->proj_out(0));
       ctrl_path.push(cn->proj_out(0)->unique_out());
-      Node* catchproj = cn->proj_out(0)->unique_out()->as_Catch()->proj_out(0);
+      Node* catchproj = cn->proj_out(0)->unique_out()->as_Catch()->proj_out_or_null(0);
       if (catchproj != NULL) {
         ctrl_path.push(catchproj);
       }
@@ -1035,13 +1035,13 @@
   // by calls in the region.
   _stringopts->_visited.Clear();
   Node_List worklist;
-  Node* final_result = _end->proj_out(TypeFunc::Parms);
+  Node* final_result = _end->proj_out_or_null(TypeFunc::Parms);
   for (uint i = 0; i < _control.size(); i++) {
     CallNode* cnode = _control.at(i)->isa_Call();
     if (cnode != NULL) {
       _stringopts->_visited.test_set(cnode->_idx);
     }
-    Node* result = cnode != NULL ? cnode->proj_out(TypeFunc::Parms) : NULL;
+    Node* result = cnode != NULL ? cnode->proj_out_or_null(TypeFunc::Parms) : NULL;
     if (result != NULL && result != final_result) {
       worklist.push(result);
     }
--- a/src/hotspot/share/opto/superword.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/opto/superword.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2018, 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
@@ -190,7 +190,7 @@
   int *ignored_loop_nodes = NEW_RESOURCE_ARRAY(int, ignored_size);
   Node_Stack nstack((int)ignored_size);
   CountedLoopNode *cl = lpt()->_head->as_CountedLoop();
-  Node *cl_exit = cl->loopexit();
+  Node *cl_exit = cl->loopexit_or_null();
   int rpo_idx = _post_block.length();
 
   assert(rpo_idx == 0, "post loop block is empty");
--- a/src/hotspot/share/prims/jni.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/prims/jni.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -2820,7 +2820,7 @@
   EntryProbe; \
   DT_VOID_RETURN_MARK(Get##Result##ArrayRegion); \
   typeArrayOop src = typeArrayOop(JNIHandles::resolve_non_null(array)); \
-  if (start < 0 || len < 0 || ((unsigned int)start + (unsigned int)len > (unsigned int)src->length())) { \
+  if (start < 0 || len < 0 || (start > src->length() - len)) { \
     THROW(vmSymbols::java_lang_ArrayIndexOutOfBoundsException()); \
   } else { \
     if (len > 0) { \
@@ -2870,7 +2870,7 @@
   EntryProbe; \
   DT_VOID_RETURN_MARK(Set##Result##ArrayRegion); \
   typeArrayOop dst = typeArrayOop(JNIHandles::resolve_non_null(array)); \
-  if (start < 0 || len < 0 || ((unsigned int)start + (unsigned int)len > (unsigned int)dst->length())) { \
+  if (start < 0 || len < 0 || (start > dst->length() - len)) { \
     THROW(vmSymbols::java_lang_ArrayIndexOutOfBoundsException()); \
   } else { \
     if (len > 0) { \
@@ -3106,7 +3106,7 @@
   DT_VOID_RETURN_MARK(GetStringRegion);
   oop s = JNIHandles::resolve_non_null(string);
   int s_len = java_lang_String::length(s);
-  if (start < 0 || len < 0 || start + len > s_len) {
+  if (start < 0 || len < 0 || start > s_len - len) {
     THROW(vmSymbols::java_lang_StringIndexOutOfBoundsException());
   } else {
     if (len > 0) {
@@ -3132,7 +3132,7 @@
   DT_VOID_RETURN_MARK(GetStringUTFRegion);
   oop s = JNIHandles::resolve_non_null(string);
   int s_len = java_lang_String::length(s);
-  if (start < 0 || len < 0 || start + len > s_len) {
+  if (start < 0 || len < 0 || start > s_len - len) {
     THROW(vmSymbols::java_lang_StringIndexOutOfBoundsException());
   } else {
     //%note jni_7
--- a/src/hotspot/share/prims/jvmtiTagMap.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/prims/jvmtiTagMap.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -30,6 +30,7 @@
 #include "code/codeCache.hpp"
 #include "jvmtifiles/jvmtiEnv.hpp"
 #include "memory/resourceArea.hpp"
+#include "oops/access.inline.hpp"
 #include "oops/instanceMirrorKlass.hpp"
 #include "oops/objArrayKlass.hpp"
 #include "oops/objArrayOop.inline.hpp"
@@ -52,10 +53,6 @@
 #include "runtime/vm_operations.hpp"
 #include "services/serviceUtil.hpp"
 #include "utilities/macros.hpp"
-#if INCLUDE_ALL_GCS
-#include "gc/g1/g1SATBCardTableModRefBS.hpp"
-#include "gc/parallel/parallelScavengeHeap.hpp"
-#endif // INCLUDE_ALL_GCS
 
 // JvmtiTagHashmapEntry
 //
@@ -78,22 +75,31 @@
   }
 
   // constructor
-  JvmtiTagHashmapEntry(oop object, jlong tag)         { init(object, tag); }
+  JvmtiTagHashmapEntry(oop object, jlong tag) { init(object, tag); }
 
  public:
 
   // accessor methods
-  inline oop object() const                           { return _object; }
-  inline oop* object_addr()                           { return &_object; }
-  inline jlong tag() const                            { return _tag; }
+  inline oop* object_addr() { return &_object; }
+  inline oop object()       { return RootAccess<ON_PHANTOM_OOP_REF>::oop_load(object_addr()); }
+  // Peek at the object without keeping it alive. The returned object must be
+  // kept alive using a normal access if it leaks out of a thread transition from VM.
+  inline oop object_peek()  {
+    return RootAccess<ON_PHANTOM_OOP_REF | AS_NO_KEEPALIVE>::oop_load(object_addr());
+  }
+  inline jlong tag() const  { return _tag; }
 
   inline void set_tag(jlong tag) {
     assert(tag != 0, "can't be zero");
     _tag = tag;
   }
 
-  inline JvmtiTagHashmapEntry* next() const             { return _next; }
-  inline void set_next(JvmtiTagHashmapEntry* next)      { _next = next; }
+  inline bool equals(oop object) {
+    return object == object_peek();
+  }
+
+  inline JvmtiTagHashmapEntry* next() const        { return _next; }
+  inline void set_next(JvmtiTagHashmapEntry* next) { _next = next; }
 };
 
 
@@ -211,7 +217,7 @@
       JvmtiTagHashmapEntry* entry = _table[i];
       while (entry != NULL) {
         JvmtiTagHashmapEntry* next = entry->next();
-        oop key = entry->object();
+        oop key = entry->object_peek();
         assert(key != NULL, "jni weak reference cleared!!");
         unsigned int h = hash(key, new_size);
         JvmtiTagHashmapEntry* anchor = new_table[h];
@@ -304,7 +310,7 @@
     unsigned int h = hash(key);
     JvmtiTagHashmapEntry* entry = _table[h];
     while (entry != NULL) {
-      if (entry->object() == key) {
+      if (entry->equals(key)) {
          return entry;
       }
       entry = entry->next();
@@ -345,7 +351,7 @@
     JvmtiTagHashmapEntry* entry = _table[h];
     JvmtiTagHashmapEntry* prev = NULL;
     while (entry != NULL) {
-      if (key == entry->object()) {
+      if (entry->equals(key)) {
         break;
       }
       prev = entry;
@@ -1535,16 +1541,12 @@
   void do_entry(JvmtiTagHashmapEntry* entry) {
     for (int i=0; i<_tag_count; i++) {
       if (_tags[i] == entry->tag()) {
+        // The reference in this tag map could be the only (implicitly weak)
+        // reference to that object. If we hand it out, we need to keep it live wrt
+        // SATB marking similar to other j.l.ref.Reference referents. This is
+        // achieved by using a phantom load in the object() accessor.
         oop o = entry->object();
         assert(o != NULL && Universe::heap()->is_in_reserved(o), "sanity check");
-#if INCLUDE_ALL_GCS
-        if (UseG1GC) {
-          // The reference in this tag map could be the only (implicitly weak)
-          // reference to that object. If we hand it out, we need to keep it live wrt
-          // SATB marking similar to other j.l.ref.Reference referents.
-          G1SATBCardTableModRefBS::enqueue(o);
-        }
-#endif
         jobject ref = JNIHandles::make_local(JavaThread::current(), o);
         _object_results->append(ref);
         _tag_results->append((uint64_t)entry->tag());
@@ -3363,10 +3365,8 @@
     while (entry != NULL) {
       JvmtiTagHashmapEntry* next = entry->next();
 
-      oop* obj = entry->object_addr();
-
       // has object been GC'ed
-      if (!is_alive->do_object_b(entry->object())) {
+      if (!is_alive->do_object_b(entry->object_peek())) {
         // grab the tag
         jlong tag = entry->tag();
         guarantee(tag != 0, "checking");
@@ -3384,7 +3384,7 @@
         ++freed;
       } else {
         f->do_oop(entry->object_addr());
-        oop new_oop = entry->object();
+        oop new_oop = entry->object_peek();
 
         // if the object has moved then re-hash it and move its
         // entry to its new location.
@@ -3418,7 +3418,7 @@
   // Re-add all the entries which were kept aside
   while (delayed_add != NULL) {
     JvmtiTagHashmapEntry* next = delayed_add->next();
-    unsigned int pos = JvmtiTagHashmap::hash(delayed_add->object(), size);
+    unsigned int pos = JvmtiTagHashmap::hash(delayed_add->object_peek(), size);
     delayed_add->set_next(table[pos]);
     table[pos] = delayed_add;
     delayed_add = next;
--- a/src/hotspot/share/prims/resolvedMethodTable.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/prims/resolvedMethodTable.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -25,6 +25,7 @@
 #include "precompiled.hpp"
 #include "gc/shared/gcLocker.hpp"
 #include "memory/allocation.hpp"
+#include "oops/access.inline.hpp"
 #include "oops/oop.inline.hpp"
 #include "oops/method.hpp"
 #include "oops/symbol.hpp"
@@ -33,10 +34,20 @@
 #include "runtime/mutexLocker.hpp"
 #include "utilities/hashtable.inline.hpp"
 #include "utilities/macros.hpp"
-#if INCLUDE_ALL_GCS
-#include "gc/g1/g1SATBCardTableModRefBS.hpp"
-#endif
+
+
+oop ResolvedMethodEntry::object() {
+  return RootAccess<ON_PHANTOM_OOP_REF>::oop_load(literal_addr());
+}
 
+oop ResolvedMethodEntry::object_no_keepalive() {
+  // The AS_NO_KEEPALIVE peeks at the oop without keeping it alive.
+  // This is dangerous in general but is okay if the loaded oop does
+  // not leak out past a thread transition where a safepoint can happen.
+  // A subsequent oop_load without AS_NO_KEEPALIVE (the object() accessor)
+  // keeps the oop alive before doing so.
+  return RootAccess<ON_PHANTOM_OOP_REF | AS_NO_KEEPALIVE>::oop_load(literal_addr());
+}
 
 ResolvedMethodTable::ResolvedMethodTable()
   : Hashtable<oop, mtClass>(_table_size, sizeof(ResolvedMethodEntry)) { }
@@ -44,13 +55,18 @@
 oop ResolvedMethodTable::lookup(int index, unsigned int hash, Method* method) {
   for (ResolvedMethodEntry* p = bucket(index); p != NULL; p = p->next()) {
     if (p->hash() == hash) {
-      oop target = p->literal();
+
+      // Peek the object to check if it is the right target.
+      oop target = p->object_no_keepalive();
+
       // The method is in the table as a target already
       if (java_lang_invoke_ResolvedMethodName::vmtarget(target) == method) {
         ResourceMark rm;
         log_debug(membername, table) ("ResolvedMethod entry found for %s index %d",
                                        method->name_and_sig_as_C_string(), index);
-        return target;
+        // The object() accessor makes sure the target object is kept alive before
+        // leaking out.
+        return p->object();
       }
     }
   }
@@ -70,18 +86,6 @@
   return lookup(index, hash, method);
 }
 
-// Tell the GC that this oop was looked up in the table
-static void ensure_oop_alive(oop mname) {
-  // A lookup in the ResolvedMethodTable could return an object that was previously
-  // considered dead. The SATB part of G1 needs to get notified about this
-  // potential resurrection, otherwise the marking might not find the object.
-#if INCLUDE_ALL_GCS
-  if (UseG1GC && mname != NULL) {
-    G1SATBCardTableModRefBS::enqueue(mname);
-  }
-#endif
-}
-
 oop ResolvedMethodTable::basic_add(Method* method, oop rmethod_name) {
   assert_locked_or_safepoint(ResolvedMethodTable_lock);
 
@@ -91,7 +95,6 @@
   // One was added while aquiring the lock
   oop entry = lookup(index, hash, method);
   if (entry != NULL) {
-    ensure_oop_alive(entry);
     return entry;
   }
 
@@ -100,14 +103,13 @@
   ResourceMark rm;
   log_debug(membername, table) ("ResolvedMethod entry added for %s index %d",
                                  method->name_and_sig_as_C_string(), index);
-  return p->literal();
+  return rmethod_name;
 }
 
 ResolvedMethodTable* ResolvedMethodTable::_the_table = NULL;
 
 oop ResolvedMethodTable::find_method(Method* method) {
   oop entry = _the_table->lookup(method);
-  ensure_oop_alive(entry);
   return entry;
 }
 
@@ -147,12 +149,12 @@
     ResolvedMethodEntry* entry = _the_table->bucket(i);
     while (entry != NULL) {
       _oops_counted++;
-      if (is_alive->do_object_b(entry->literal())) {
+      if (is_alive->do_object_b(entry->object_no_keepalive())) {
         p = entry->next_addr();
       } else {
         _oops_removed++;
         if (log_is_enabled(Debug, membername, table)) {
-          Method* m = (Method*)java_lang_invoke_ResolvedMethodName::vmtarget(entry->literal());
+          Method* m = (Method*)java_lang_invoke_ResolvedMethodName::vmtarget(entry->object_no_keepalive());
           ResourceMark rm;
           log_debug(membername, table) ("ResolvedMethod entry removed for %s index %d",
                                            m->name_and_sig_as_C_string(), i);
@@ -185,7 +187,7 @@
     ResolvedMethodEntry* entry = bucket(i);
     while (entry != NULL) {
       tty->print("%d : ", i);
-      oop rmethod_name = entry->literal();
+      oop rmethod_name = entry->object_no_keepalive();
       rmethod_name->print();
       Method* m = (Method*)java_lang_invoke_ResolvedMethodName::vmtarget(rmethod_name);
       m->print();
@@ -203,8 +205,7 @@
   for (int i = 0; i < _the_table->table_size(); ++i) {
     ResolvedMethodEntry* entry = _the_table->bucket(i);
     while (entry != NULL) {
-
-      oop mem_name = entry->literal();
+      oop mem_name = entry->object_no_keepalive();
       Method* old_method = (Method*)java_lang_invoke_ResolvedMethodName::vmtarget(mem_name);
 
       if (old_method->is_old()) {
--- a/src/hotspot/share/prims/resolvedMethodTable.hpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/prims/resolvedMethodTable.hpp	Fri Jan 19 09:32:10 2018 -0800
@@ -44,6 +44,9 @@
     return (ResolvedMethodEntry**)HashtableEntry<oop, mtClass>::next_addr();
   }
 
+  oop object();
+  oop object_no_keepalive();
+
   void print_on(outputStream* st) const;
 };
 
--- a/src/hotspot/share/runtime/arguments.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/runtime/arguments.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, 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
@@ -63,7 +63,11 @@
 #endif
 
 // Note: This is a special bug reporting site for the JVM
-#define DEFAULT_VENDOR_URL_BUG "http://bugreport.java.com/bugreport/crash.jsp"
+#ifdef VENDOR_URL_VM_BUG
+# define DEFAULT_VENDOR_URL_BUG VENDOR_URL_VM_BUG
+#else
+# define DEFAULT_VENDOR_URL_BUG "http://bugreport.java.com/bugreport/crash.jsp"
+#endif
 #define DEFAULT_JAVA_LAUNCHER  "generic"
 
 char*  Arguments::_jvm_flags_file               = NULL;
@@ -523,6 +527,7 @@
   { "ConvertSleepToYield",           JDK_Version::jdk(9),      JDK_Version::jdk(10), JDK_Version::jdk(11) },
   { "ConvertYieldToSleep",           JDK_Version::jdk(9),      JDK_Version::jdk(10), JDK_Version::jdk(11) },
   { "MinSleepInterval",              JDK_Version::jdk(9),      JDK_Version::jdk(10), JDK_Version::jdk(11) },
+  { "CheckAssertionStatusDirectives",JDK_Version::undefined(), JDK_Version::jdk(11), JDK_Version::jdk(12) },
   { "PermSize",                      JDK_Version::undefined(), JDK_Version::jdk(8),  JDK_Version::undefined() },
   { "MaxPermSize",                   JDK_Version::undefined(), JDK_Version::jdk(8),  JDK_Version::undefined() },
   { "SharedReadWriteSize",           JDK_Version::undefined(), JDK_Version::jdk(10), JDK_Version::undefined() },
--- a/src/hotspot/share/runtime/globals.hpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/runtime/globals.hpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, 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
@@ -893,9 +893,6 @@
   develop(bool, TraceJavaAssertions, false,                                 \
           "Trace java language assertions")                                 \
                                                                             \
-  notproduct(bool, CheckAssertionStatusDirectives, false,                   \
-          "Temporary - see javaClasses.cpp")                                \
-                                                                            \
   notproduct(bool, PrintMallocFree, false,                                  \
           "Trace calls to C heap malloc/free allocation")                   \
                                                                             \
--- a/src/hotspot/share/runtime/init.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/runtime/init.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, 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
@@ -131,6 +131,7 @@
   InterfaceSupport_init();
   SharedRuntime::generate_stubs();
   universe2_init();  // dependent on codeCache_init and stubRoutines_init1
+  javaClasses_init();// must happen after vtable initialization, before referenceProcessor_init
   referenceProcessor_init();
   jni_handles_init();
 #if INCLUDE_VM_STRUCTS
@@ -150,7 +151,6 @@
   if (!universe_post_init()) {
     return JNI_ERR;
   }
-  javaClasses_init();   // must happen after vtable initialization
   stubRoutines_init2(); // note: StubRoutines need 2-phase init
   MethodHandles::generate_adapters();
 
--- a/src/hotspot/share/runtime/os.hpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/runtime/os.hpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, 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
@@ -778,7 +778,6 @@
   static void* signal(int signal_number, void* handler);
   static void  signal_raise(int signal_number);
   static int   signal_wait();
-  static int   signal_lookup();
   static void* user_handler();
   static void  terminate_signal_thread();
   static int   sigexitnum_pd();
--- a/src/hotspot/share/runtime/vframe_hp.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/runtime/vframe_hp.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -57,61 +57,19 @@
   // There is one scv_list entry for every JVM stack state in use.
   int length = scv_list->length();
   StackValueCollection* result = new StackValueCollection(length);
-  // In rare instances set_locals may have occurred in which case
-  // there are local values that are not described by the ScopeValue anymore
-  GrowableArray<jvmtiDeferredLocalVariable*>* deferred = NULL;
+  for (int i = 0; i < length; i++) {
+    result->add(create_stack_value(scv_list->at(i)));
+  }
+
+  // Replace the original values with any stores that have been
+  // performed through compiledVFrame::update_locals.
   GrowableArray<jvmtiDeferredLocalVariableSet*>* list = thread()->deferred_locals();
   if (list != NULL ) {
     // In real life this never happens or is typically a single element search
     for (int i = 0; i < list->length(); i++) {
-      if (list->at(i)->matches((vframe*)this)) {
-        deferred = list->at(i)->locals();
-        break;
-      }
-    }
-  }
-
-  for( int i = 0; i < length; i++ ) {
-    result->add( create_stack_value(scv_list->at(i)) );
-  }
-
-  // Replace specified locals with any deferred writes that are present
-  if (deferred != NULL) {
-    for ( int l = 0;  l < deferred->length() ; l ++) {
-      jvmtiDeferredLocalVariable* val = deferred->at(l);
-      switch (val->type()) {
-      case T_BOOLEAN:
-        result->set_int_at(val->index(), val->value().z);
-        break;
-      case T_CHAR:
-        result->set_int_at(val->index(), val->value().c);
+      if (list->at(i)->matches(this)) {
+        list->at(i)->update_locals(result);
         break;
-      case T_FLOAT:
-        result->set_float_at(val->index(), val->value().f);
-        break;
-      case T_DOUBLE:
-        result->set_double_at(val->index(), val->value().d);
-        break;
-      case T_BYTE:
-        result->set_int_at(val->index(), val->value().b);
-        break;
-      case T_SHORT:
-        result->set_int_at(val->index(), val->value().s);
-        break;
-      case T_INT:
-        result->set_int_at(val->index(), val->value().i);
-        break;
-      case T_LONG:
-        result->set_long_at(val->index(), val->value().j);
-        break;
-      case T_OBJECT:
-        {
-          Handle obj(Thread::current(), (oop)val->value().l);
-          result->set_obj_at(val->index(), obj);
-        }
-        break;
-      default:
-        ShouldNotReachHere();
       }
     }
   }
@@ -126,29 +84,32 @@
 }
 
 void compiledVFrame::update_local(BasicType type, int index, jvalue value) {
+  assert(index >= 0 && index < method()->max_locals(), "out of bounds");
+  update_deferred_value(type, index, value);
+}
 
-#ifdef ASSERT
+void compiledVFrame::update_stack(BasicType type, int index, jvalue value) {
+  assert(index >= 0 && index < method()->max_stack(), "out of bounds");
+  update_deferred_value(type, index + method()->max_locals(), value);
+}
 
+void compiledVFrame::update_monitor(int index, MonitorInfo* val) {
+  assert(index >= 0, "out of bounds");
+  jvalue value;
+  value.l = (jobject) val->owner();
+  update_deferred_value(T_OBJECT, index + method()->max_locals() + method()->max_stack(), value);
+}
+
+void compiledVFrame::update_deferred_value(BasicType type, int index, jvalue value) {
   assert(fr().is_deoptimized_frame(), "frame must be scheduled for deoptimization");
-#endif /* ASSERT */
   GrowableArray<jvmtiDeferredLocalVariableSet*>* deferred = thread()->deferred_locals();
+  jvmtiDeferredLocalVariableSet* locals = NULL;
   if (deferred != NULL ) {
     // See if this vframe has already had locals with deferred writes
-    int f;
-    for ( f = 0 ; f < deferred->length() ; f++ ) {
+    for (int f = 0; f < deferred->length(); f++ ) {
       if (deferred->at(f)->matches(this)) {
-        // Matching, vframe now see if the local already had deferred write
-        GrowableArray<jvmtiDeferredLocalVariable*>* locals = deferred->at(f)->locals();
-        int l;
-        for (l = 0 ; l < locals->length() ; l++ ) {
-          if (locals->at(l)->index() == index) {
-            locals->at(l)->set_value(value);
-            return;
-          }
-        }
-        // No matching local already present. Push a new value onto the deferred collection
-        locals->push(new jvmtiDeferredLocalVariable(index, type, value));
-        return;
+        locals = deferred->at(f);
+        break;
       }
     }
     // No matching vframe must push a new vframe
@@ -158,9 +119,12 @@
     deferred =  new(ResourceObj::C_HEAP, mtCompiler) GrowableArray<jvmtiDeferredLocalVariableSet*> (1, true);
     thread()->set_deferred_locals(deferred);
   }
-  deferred->push(new jvmtiDeferredLocalVariableSet(method(), bci(), fr().id(), vframe_id()));
-  assert(deferred->top()->id() == fr().id(), "Huh? Must match");
-  deferred->top()->set_local_at(index, type, value);
+  if (locals == NULL) {
+    locals = new jvmtiDeferredLocalVariableSet(method(), bci(), fr().id(), vframe_id());
+    deferred->push(locals);
+    assert(locals->id() == fr().id(), "Huh? Must match");
+  }
+  locals->set_value_at(index, type, value);
 }
 
 StackValueCollection* compiledVFrame::expressions() const {
@@ -173,8 +137,22 @@
   // There is one scv_list entry for every JVM stack state in use.
   int length = scv_list->length();
   StackValueCollection* result = new StackValueCollection(length);
-  for( int i = 0; i < length; i++ )
-    result->add( create_stack_value(scv_list->at(i)) );
+  for (int i = 0; i < length; i++) {
+    result->add(create_stack_value(scv_list->at(i)));
+  }
+
+  // Replace the original values with any stores that have been
+  // performed through compiledVFrame::update_stack.
+  GrowableArray<jvmtiDeferredLocalVariableSet*>* list = thread()->deferred_locals();
+  if (list != NULL ) {
+    // In real life this never happens or is typically a single element search
+    for (int i = 0; i < list->length(); i++) {
+      if (list->at(i)->matches(this)) {
+        list->at(i)->update_stack(result);
+        break;
+      }
+    }
+  }
 
   return result;
 }
@@ -236,6 +214,20 @@
                                    mv->eliminated(), false));
     }
   }
+
+  // Replace the original values with any stores that have been
+  // performed through compiledVFrame::update_monitors.
+  GrowableArray<jvmtiDeferredLocalVariableSet*>* list = thread()->deferred_locals();
+  if (list != NULL ) {
+    // In real life this never happens or is typically a single element search
+    for (int i = 0; i < list->length(); i++) {
+      if (list->at(i)->matches(this)) {
+        list->at(i)->update_monitors(result);
+        break;
+      }
+    }
+  }
+
   return result;
 }
 
@@ -332,14 +324,14 @@
 }
 
 jvmtiDeferredLocalVariableSet::~jvmtiDeferredLocalVariableSet() {
-  for (int i = 0; i < _locals->length() ; i++ ) {
+  for (int i = 0; i < _locals->length(); i++ ) {
     delete _locals->at(i);
   }
   // Free growableArray and c heap for elements
   delete _locals;
 }
 
-bool jvmtiDeferredLocalVariableSet::matches(vframe* vf) {
+bool jvmtiDeferredLocalVariableSet::matches(const vframe* vf) {
   if (!vf->is_compiled_frame()) return false;
   compiledVFrame* cvf = (compiledVFrame*)vf;
   if (cvf->fr().id() == id() && cvf->vframe_id() == vframe_id()) {
@@ -349,24 +341,93 @@
   return false;
 }
 
-void jvmtiDeferredLocalVariableSet::set_local_at(int idx, BasicType type, jvalue val) {
-  int i;
-  for ( i = 0 ; i < locals()->length() ; i++ ) {
-    if ( locals()->at(i)->index() == idx) {
-      assert(locals()->at(i)->type() == type, "Wrong type");
-      locals()->at(i)->set_value(val);
+void jvmtiDeferredLocalVariableSet::set_value_at(int idx, BasicType type, jvalue val) {
+  for (int i = 0; i < _locals->length(); i++) {
+    if (_locals->at(i)->index() == idx) {
+      assert(_locals->at(i)->type() == type, "Wrong type");
+      _locals->at(i)->set_value(val);
       return;
     }
   }
-  locals()->push(new jvmtiDeferredLocalVariable(idx, type, val));
+  _locals->push(new jvmtiDeferredLocalVariable(idx, type, val));
 }
 
+void jvmtiDeferredLocalVariableSet::update_value(StackValueCollection* locals, BasicType type, int index, jvalue value) {
+  switch (type) {
+    case T_BOOLEAN:
+      locals->set_int_at(index, value.z);
+      break;
+    case T_CHAR:
+      locals->set_int_at(index, value.c);
+      break;
+    case T_FLOAT:
+      locals->set_float_at(index, value.f);
+      break;
+    case T_DOUBLE:
+      locals->set_double_at(index, value.d);
+      break;
+    case T_BYTE:
+      locals->set_int_at(index, value.b);
+      break;
+    case T_SHORT:
+      locals->set_int_at(index, value.s);
+      break;
+    case T_INT:
+      locals->set_int_at(index, value.i);
+      break;
+    case T_LONG:
+      locals->set_long_at(index, value.j);
+      break;
+    case T_OBJECT:
+      {
+        Handle obj(Thread::current(), (oop)value.l);
+        locals->set_obj_at(index, obj);
+      }
+      break;
+    default:
+      ShouldNotReachHere();
+  }
+}
+
+void jvmtiDeferredLocalVariableSet::update_locals(StackValueCollection* locals) {
+  for (int l = 0; l < _locals->length(); l ++) {
+    jvmtiDeferredLocalVariable* val = _locals->at(l);
+    if (val->index() >= 0 && val->index() < method()->max_locals()) {
+      update_value(locals, val->type(), val->index(), val->value());
+    }
+  }
+}
+
+
+void jvmtiDeferredLocalVariableSet::update_stack(StackValueCollection* expressions) {
+  for (int l = 0; l < _locals->length(); l ++) {
+    jvmtiDeferredLocalVariable* val = _locals->at(l);
+    if (val->index() >= method()->max_locals() && val->index() < method()->max_locals() + method()->max_stack()) {
+      update_value(expressions, val->type(), val->index() - method()->max_locals(), val->value());
+    }
+  }
+}
+
+
+void jvmtiDeferredLocalVariableSet::update_monitors(GrowableArray<MonitorInfo*>* monitors) {
+  for (int l = 0; l < _locals->length(); l ++) {
+    jvmtiDeferredLocalVariable* val = _locals->at(l);
+    if (val->index() >= method()->max_locals() + method()->max_stack()) {
+      int lock_index = val->index() - (method()->max_locals() + method()->max_stack());
+      MonitorInfo* info = monitors->at(lock_index);
+      MonitorInfo* new_info = new MonitorInfo((oopDesc*)val->value().l, info->lock(), info->eliminated(), info->owner_is_scalar_replaced());
+      monitors->at_put(lock_index, new_info);
+    }
+  }
+}
+
+
 void jvmtiDeferredLocalVariableSet::oops_do(OopClosure* f) {
   // The Method* is on the stack so a live activation keeps it alive
   // either by mirror in interpreter or code in compiled code.
-  for ( int i = 0; i < locals()->length(); i++ ) {
-    if ( locals()->at(i)->type() == T_OBJECT) {
-      f->do_oop(locals()->at(i)->oop_addr());
+  for (int i = 0; i < _locals->length(); i++) {
+    if (_locals->at(i)->type() == T_OBJECT) {
+      f->do_oop(_locals->at(i)->oop_addr());
     }
   }
 }
--- a/src/hotspot/share/runtime/vframe_hp.hpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/runtime/vframe_hp.hpp	Fri Jan 19 09:32:10 2018 -0800
@@ -51,6 +51,8 @@
     return (compiledVFrame*) vf;
   }
 
+  void update_deferred_value(BasicType type, int index, jvalue value);
+
  public:
   // Constructors
   compiledVFrame(const frame* fr, const RegisterMap* reg_map, JavaThread* thread, CompiledMethod* nm);
@@ -58,6 +60,12 @@
   // Update a local in a compiled frame. Update happens when deopt occurs
   void update_local(BasicType type, int index, jvalue value);
 
+  // Update an expression stack value in a compiled frame. Update happens when deopt occurs
+  void update_stack(BasicType type, int index, jvalue value);
+
+  // Update a lock value in a compiled frame. Update happens when deopt occurs
+  void update_monitor(int index, MonitorInfo* value);
+
   // Returns the active nmethod
   CompiledMethod*  code() const;
 
@@ -91,6 +99,8 @@
 
 class jvmtiDeferredLocalVariable;
 class jvmtiDeferredLocalVariableSet : public CHeapObj<mtCompiler> {
+  friend class compiledVFrame;
+
 private:
 
   Method* _method;
@@ -99,17 +109,23 @@
   int _vframe_id;
   GrowableArray<jvmtiDeferredLocalVariable*>* _locals;
 
+  void                              update_value(StackValueCollection* locals, BasicType type, int index, jvalue value);
+
+  void                              set_value_at(int idx, BasicType typ, jvalue val);
+
  public:
   // JVM state
   Method*                           method()         const  { return _method; }
   int                               bci()            const  { return _bci; }
   intptr_t*                         id()             const  { return _id; }
   int                               vframe_id()      const  { return _vframe_id; }
-  GrowableArray<jvmtiDeferredLocalVariable*>* locals()         const  { return _locals; }
-  void                              set_local_at(int idx, BasicType typ, jvalue val);
+
+  void                              update_locals(StackValueCollection* locals);
+  void                              update_stack(StackValueCollection* locals);
+  void                              update_monitors(GrowableArray<MonitorInfo*>* monitors);
 
   // Does the vframe match this jvmtiDeferredLocalVariableSet
-  bool                              matches(vframe* vf);
+  bool                              matches(const vframe* vf);
   // GC
   void                              oops_do(OopClosure* f);
 
--- a/src/hotspot/share/runtime/vmStructs.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/runtime/vmStructs.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -233,7 +233,7 @@
   nonstatic_field(ArrayKlass,                  _dimension,                                    int)                                   \
   volatile_nonstatic_field(ArrayKlass,         _higher_dimension,                             Klass*)                                \
   volatile_nonstatic_field(ArrayKlass,         _lower_dimension,                              Klass*)                                \
-  nonstatic_field(CompiledICHolder,            _holder_method,                                Method*)                               \
+  nonstatic_field(CompiledICHolder,            _holder_metadata,                              Metadata*)                               \
   nonstatic_field(CompiledICHolder,            _holder_klass,                                 Klass*)                                \
   nonstatic_field(ConstantPool,                _tags,                                         Array<u1>*)                            \
   nonstatic_field(ConstantPool,                _cache,                                        ConstantPoolCache*)                    \
--- a/src/hotspot/share/runtime/vm_operations.hpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/runtime/vm_operations.hpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, 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
@@ -67,9 +67,8 @@
   template(CGC_Operation)                         \
   template(CMS_Initial_Mark)                      \
   template(CMS_Final_Remark)                      \
+  template(G1CollectForAllocation)                \
   template(G1CollectFull)                         \
-  template(G1CollectForAllocation)                \
-  template(G1IncCollectionPause)                  \
   template(HandshakeOneThread)                    \
   template(HandshakeAllThreads)                   \
   template(HandshakeFallback)                     \
--- a/src/hotspot/share/utilities/vmError.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/hotspot/share/utilities/vmError.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2018, 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
@@ -243,11 +243,12 @@
           RegisterMap map((JavaThread*)t, false); // No update
           fr = fr.sender(&map);
         } else {
+          // is_first_C_frame() does only simple checks for frame pointer,
+          // it will pass if java compiled code has a pointer in EBP.
+          if (os::is_first_C_frame(&fr)) break;
           fr = os::get_sender_for_C_frame(&fr);
         }
       } else {
-        // is_first_C_frame() does only simple checks for frame pointer,
-        // it will pass if java compiled code has a pointer in EBP.
         if (os::is_first_C_frame(&fr)) break;
         fr = os::get_sender_for_C_frame(&fr);
       }
--- a/src/java.base/macosx/native/libosxsecurity/KeystoreImpl.m	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.base/macosx/native/libosxsecurity/KeystoreImpl.m	Fri Jan 19 09:32:10 2018 -0800
@@ -439,6 +439,11 @@
                 goto errOut;
             }
             passwordStrRef = CFStringCreateWithCharacters(kCFAllocatorDefault, passwordChars, passwordLen);
+
+            // clear the password and release
+            memset(passwordChars, 0, passwordLen);
+            (*env)->ReleaseCharArrayElements(env, passwordObj, passwordChars,
+                JNI_ABORT);
         }
     }
 
@@ -527,8 +532,19 @@
 
     if (passwordObj) {
         passwordLen = (*env)->GetArrayLength(env, passwordObj);
-        passwordChars = (*env)->GetCharArrayElements(env, passwordObj, NULL);
-        passwordStrRef = CFStringCreateWithCharacters(kCFAllocatorDefault, passwordChars, passwordLen);
+
+        if (passwordLen > 0) {
+            passwordChars = (*env)->GetCharArrayElements(env, passwordObj, NULL);
+            if (passwordChars == NULL) {
+                goto errOut;
+            }
+            passwordStrRef = CFStringCreateWithCharacters(kCFAllocatorDefault, passwordChars, passwordLen);
+
+            // clear the password and release
+            memset(passwordChars, 0, passwordLen);
+            (*env)->ReleaseCharArrayElements(env, passwordObj, passwordChars,
+                JNI_ABORT);
+        }
     }
 
     paramBlock.version = SEC_KEY_IMPORT_EXPORT_PARAMS_VERSION;
--- a/src/java.base/share/classes/com/sun/crypto/provider/DESKey.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.base/share/classes/com/sun/crypto/provider/DESKey.java	Fri Jan 19 09:32:10 2018 -0800
@@ -25,6 +25,7 @@
 
 package com.sun.crypto.provider;
 
+import java.lang.ref.Reference;
 import java.security.MessageDigest;
 import java.security.KeyRep;
 import java.security.InvalidKeyException;
@@ -86,7 +87,12 @@
     public byte[] getEncoded() {
         // Return a copy of the key, rather than a reference,
         // so that the key data cannot be modified from outside
-        return this.key.clone();
+
+        // The key is zeroized by finalize()
+        // The reachability fence ensures finalize() isn't called early
+        byte[] result = key.clone();
+        Reference.reachabilityFence(this);
+        return result;
     }
 
     public String getAlgorithm() {
--- a/src/java.base/share/classes/com/sun/crypto/provider/DESedeKey.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.base/share/classes/com/sun/crypto/provider/DESedeKey.java	Fri Jan 19 09:32:10 2018 -0800
@@ -25,6 +25,7 @@
 
 package com.sun.crypto.provider;
 
+import java.lang.ref.Reference;
 import java.security.MessageDigest;
 import java.security.KeyRep;
 import java.security.InvalidKeyException;
@@ -86,7 +87,11 @@
     }
 
     public byte[] getEncoded() {
-        return this.key.clone();
+        // The key is zeroized by finalize()
+        // The reachability fence ensures finalize() isn't called early
+        byte[] result = key.clone();
+        Reference.reachabilityFence(this);
+        return result;
     }
 
     public String getAlgorithm() {
--- a/src/java.base/share/classes/com/sun/crypto/provider/DHKeyAgreement.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.base/share/classes/com/sun/crypto/provider/DHKeyAgreement.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, 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,11 +28,13 @@
 import java.util.*;
 import java.lang.*;
 import java.math.BigInteger;
+import java.security.AccessController;
 import java.security.InvalidAlgorithmParameterException;
 import java.security.InvalidKeyException;
 import java.security.Key;
 import java.security.NoSuchAlgorithmException;
 import java.security.SecureRandom;
+import java.security.PrivilegedAction;
 import java.security.ProviderException;
 import java.security.spec.AlgorithmParameterSpec;
 import java.security.spec.InvalidKeySpecException;
@@ -60,6 +62,17 @@
     private BigInteger x = BigInteger.ZERO; // the private value
     private BigInteger y = BigInteger.ZERO;
 
+    private static class AllowKDF {
+
+        private static final boolean VALUE = getValue();
+
+        private static boolean getValue() {
+            return AccessController.doPrivileged(
+                (PrivilegedAction<Boolean>)
+                () -> Boolean.getBoolean("jdk.crypto.KeyAgreement.legacyKDF"));
+        }
+    }
+
     /**
      * Empty constructor
      */
@@ -367,6 +380,14 @@
         if (algorithm == null) {
             throw new NoSuchAlgorithmException("null algorithm");
         }
+
+        if (!algorithm.equalsIgnoreCase("TlsPremasterSecret") &&
+            !AllowKDF.VALUE) {
+
+            throw new NoSuchAlgorithmException("Unsupported secret key "
+                                               + "algorithm: " + algorithm);
+        }
+
         byte[] secret = engineGenerateSecret();
         if (algorithm.equalsIgnoreCase("DES")) {
             // DES
--- a/src/java.base/share/classes/com/sun/crypto/provider/PBEKey.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.base/share/classes/com/sun/crypto/provider/PBEKey.java	Fri Jan 19 09:32:10 2018 -0800
@@ -25,6 +25,7 @@
 
 package com.sun.crypto.provider;
 
+import java.lang.ref.Reference;
 import java.security.MessageDigest;
 import java.security.KeyRep;
 import java.security.spec.InvalidKeySpecException;
@@ -80,7 +81,11 @@
     }
 
     public byte[] getEncoded() {
-        return this.key.clone();
+        // The key is zeroized by finalize()
+        // The reachability fence ensures finalize() isn't called early
+        byte[] result = key.clone();
+        Reference.reachabilityFence(this);
+        return result;
     }
 
     public String getAlgorithm() {
--- a/src/java.base/share/classes/com/sun/crypto/provider/PBKDF2KeyImpl.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.base/share/classes/com/sun/crypto/provider/PBKDF2KeyImpl.java	Fri Jan 19 09:32:10 2018 -0800
@@ -26,6 +26,7 @@
 package com.sun.crypto.provider;
 
 import java.io.ObjectStreamException;
+import java.lang.ref.Reference;
 import java.nio.ByteBuffer;
 import java.nio.CharBuffer;
 import java.nio.charset.Charset;
@@ -208,7 +209,11 @@
     }
 
     public byte[] getEncoded() {
-        return key.clone();
+        // The key is zeroized by finalize()
+        // The reachability fence ensures finalize() isn't called early
+        byte[] result = key.clone();
+        Reference.reachabilityFence(this);
+        return result;
     }
 
     public String getAlgorithm() {
@@ -220,7 +225,11 @@
     }
 
     public char[] getPassword() {
-        return passwd.clone();
+        // The password is zeroized by finalize()
+        // The reachability fence ensures finalize() isn't called early
+        char[] result = passwd.clone();
+        Reference.reachabilityFence(this);
+        return result;
     }
 
     public byte[] getSalt() {
--- a/src/java.base/share/classes/java/lang/Runtime.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.base/share/classes/java/lang/Runtime.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1995, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1995, 2018, 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
@@ -1099,16 +1099,23 @@
                     m.group(VersionPattern.OPT_GROUP));
 
             // empty '+'
-            if ((m.group(VersionPattern.PLUS_GROUP) != null)
-                    && !build.isPresent()) {
-                if (optional.isPresent()) {
-                    if (pre.isPresent())
-                        throw new IllegalArgumentException("'+' found with"
-                            + " pre-release and optional components:'" + s
-                            + "'");
+            if (!build.isPresent()) {
+                if (m.group(VersionPattern.PLUS_GROUP) != null) {
+                    if (optional.isPresent()) {
+                        if (pre.isPresent())
+                            throw new IllegalArgumentException("'+' found with"
+                                + " pre-release and optional components:'" + s
+                                + "'");
+                    } else {
+                        throw new IllegalArgumentException("'+' found with neither"
+                            + " build or optional components: '" + s + "'");
+                    }
                 } else {
-                    throw new IllegalArgumentException("'+' found with neither"
-                        + " build or optional components: '" + s + "'");
+                    if (optional.isPresent() && !pre.isPresent()) {
+                        throw new IllegalArgumentException("optional component"
+                            + " must be preceeded by a pre-release component"
+                            + " or '+': '" + s + "'");
+                    }
                 }
             }
             return new Version(List.of(version), pre, build, optional);
--- a/src/java.base/share/classes/java/lang/invoke/DirectMethodHandle.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.base/share/classes/java/lang/invoke/DirectMethodHandle.java	Fri Jan 19 09:32:10 2018 -0800
@@ -80,13 +80,20 @@
             mtype = mtype.insertParameterTypes(0, receiver);
         }
         if (!member.isField()) {
-            if (refKind == REF_invokeSpecial) {
-                member = member.asSpecial();
-                LambdaForm lform = preparedLambdaForm(member);
-                return new Special(mtype, lform, member);
-            } else {
-                LambdaForm lform = preparedLambdaForm(member);
-                return new DirectMethodHandle(mtype, lform, member);
+            switch (refKind) {
+                case REF_invokeSpecial: {
+                    member = member.asSpecial();
+                    LambdaForm lform = preparedLambdaForm(member);
+                    return new Special(mtype, lform, member);
+                }
+                case REF_invokeInterface: {
+                    LambdaForm lform = preparedLambdaForm(member);
+                    return new Interface(mtype, lform, member, receiver);
+                }
+                default: {
+                    LambdaForm lform = preparedLambdaForm(member);
+                    return new DirectMethodHandle(mtype, lform, member);
+                }
             }
         } else {
             LambdaForm lform = preparedFieldLambdaForm(member);
@@ -190,6 +197,7 @@
     static LambdaForm makePreparedLambdaForm(MethodType mtype, int which) {
         boolean needsInit = (which == LF_INVSTATIC_INIT);
         boolean doesAlloc = (which == LF_NEWINVSPECIAL);
+        boolean needsReceiverCheck = (which == LF_INVINTERFACE);
         String linkerName;
         LambdaForm.Kind kind;
         switch (which) {
@@ -219,6 +227,7 @@
         int nameCursor = ARG_LIMIT;
         final int NEW_OBJ     = (doesAlloc ? nameCursor++ : -1);
         final int GET_MEMBER  = nameCursor++;
+        final int CHECK_RECEIVER = (needsReceiverCheck ? nameCursor++ : -1);
         final int LINKER_CALL = nameCursor++;
         Name[] names = arguments(nameCursor - ARG_LIMIT, mtype.invokerType());
         assert(names.length == nameCursor);
@@ -233,6 +242,10 @@
         }
         assert(findDirectMethodHandle(names[GET_MEMBER]) == names[DMH_THIS]);
         Object[] outArgs = Arrays.copyOfRange(names, ARG_BASE, GET_MEMBER+1, Object[].class);
+        if (needsReceiverCheck) {
+            names[CHECK_RECEIVER] = new Name(getFunction(NF_checkReceiver), names[DMH_THIS], names[ARG_BASE]);
+            outArgs[0] = names[CHECK_RECEIVER];
+        }
         assert(outArgs[outArgs.length-1] == names[GET_MEMBER]);  // look, shifted args!
         int result = LAST_RESULT;
         if (doesAlloc) {
@@ -376,6 +389,29 @@
         }
     }
 
+    /** This subclass represents invokeinterface instructions. */
+    static class Interface extends DirectMethodHandle {
+        private final Class<?> refc;
+        private Interface(MethodType mtype, LambdaForm form, MemberName member, Class<?> refc) {
+            super(mtype, form, member);
+            assert refc.isInterface() : refc;
+            this.refc = refc;
+        }
+        @Override
+        MethodHandle copyWith(MethodType mt, LambdaForm lf) {
+            return new Interface(mt, lf, member, refc);
+        }
+
+        Object checkReceiver(Object recv) {
+            if (!refc.isInstance(recv)) {
+                String msg = String.format("Class %s does not implement the requested interface %s",
+                        recv.getClass().getName(), refc.getName());
+                throw new IncompatibleClassChangeError(msg);
+            }
+            return recv;
+        }
+    }
+
     /** This subclass handles constructor references. */
     static class Constructor extends DirectMethodHandle {
         final MemberName initMethod;
@@ -738,7 +774,8 @@
             NF_allocateInstance = 8,
             NF_constructorMethod = 9,
             NF_UNSAFE = 10,
-            NF_LIMIT = 11;
+            NF_checkReceiver = 11,
+            NF_LIMIT = 12;
 
     private static final @Stable NamedFunction[] NFS = new NamedFunction[NF_LIMIT];
 
@@ -785,6 +822,11 @@
                     return new NamedFunction(
                             MemberName.getFactory()
                                     .resolveOrFail(REF_getField, member, DirectMethodHandle.class, NoSuchMethodException.class));
+                case NF_checkReceiver:
+                    member = new MemberName(Interface.class, "checkReceiver", OBJ_OBJ_TYPE, REF_invokeVirtual);
+                    return new NamedFunction(
+                        MemberName.getFactory()
+                            .resolveOrFail(REF_invokeVirtual, member, Interface.class, NoSuchMethodException.class));
                 default:
                     throw newInternalError("Unknown function: " + func);
             }
--- a/src/java.base/share/classes/java/lang/invoke/MethodHandles.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.base/share/classes/java/lang/invoke/MethodHandles.java	Fri Jan 19 09:32:10 2018 -0800
@@ -3766,6 +3766,7 @@
      * specified in the elements of the {@code filters} array.
      * The first element of the filter array corresponds to the {@code pos}
      * argument of the target, and so on in sequence.
+     * The filter functions are invoked in left to right order.
      * <p>
      * Null arguments in the array are treated as identity functions,
      * and the corresponding arguments left unchanged.
@@ -3836,11 +3837,12 @@
     MethodHandle filterArguments(MethodHandle target, int pos, MethodHandle... filters) {
         filterArgumentsCheckArity(target, pos, filters);
         MethodHandle adapter = target;
-        int curPos = pos-1;  // pre-incremented
-        for (MethodHandle filter : filters) {
-            curPos += 1;
+        // process filters in reverse order so that the invocation of
+        // the resulting adapter will invoke the filters in left-to-right order
+        for (int i = filters.length - 1; i >= 0; --i) {
+            MethodHandle filter = filters[i];
             if (filter == null)  continue;  // ignore null elements of filters
-            adapter = filterArgument(adapter, curPos, filter);
+            adapter = filterArgument(adapter, pos + i, filter);
         }
         return adapter;
     }
--- a/src/java.base/share/classes/java/util/ResourceBundle.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.base/share/classes/java/util/ResourceBundle.java	Fri Jan 19 09:32:10 2018 -0800
@@ -591,7 +591,7 @@
      */
     private static ClassLoader getLoaderForControl(Module module) {
         ClassLoader loader = getLoader(module);
-        return loader == null ? ClassLoader.getSystemClassLoader() : loader;
+        return loader == null ? ClassLoader.getPlatformClassLoader() : loader;
     }
 
     /**
--- a/src/java.base/share/classes/java/util/concurrent/ArrayBlockingQueue.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.base/share/classes/java/util/concurrent/ArrayBlockingQueue.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1608,4 +1608,30 @@
         }
     }
 
+    /**
+     * Deserializes this queue and then checks some invariants.
+     *
+     * @param s the input stream
+     * @throws ClassNotFoundException if the class of a serialized object
+     *         could not be found
+     * @throws java.io.InvalidObjectException if invariants are violated
+     * @throws java.io.IOException if an I/O error occurs
+     */
+    private void readObject(java.io.ObjectInputStream s)
+        throws java.io.IOException, ClassNotFoundException {
+
+        // Read in items array and various fields
+        s.defaultReadObject();
+
+        // Check invariants over count and index fields. Note that
+        // if putIndex==takeIndex, count can be either 0 or items.length.
+        if (items.length == 0 ||
+            takeIndex < 0 || takeIndex >= items.length ||
+            putIndex  < 0 || putIndex  >= items.length ||
+            count < 0     || count     >  items.length ||
+            Math.floorMod(putIndex - takeIndex, items.length) !=
+            Math.floorMod(count, items.length)) {
+            throw new java.io.InvalidObjectException("invariants violated");
+        }
+    }
 }
--- a/src/java.base/share/classes/java/util/stream/DoublePipeline.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.base/share/classes/java/util/stream/DoublePipeline.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -40,7 +40,6 @@
 import java.util.function.DoubleToLongFunction;
 import java.util.function.DoubleUnaryOperator;
 import java.util.function.IntFunction;
-import java.util.function.LongPredicate;
 import java.util.function.ObjDoubleConsumer;
 import java.util.function.Supplier;
 
@@ -265,6 +264,12 @@
             @Override
             Sink<Double> opWrapSink(int flags, Sink<Double> sink) {
                 return new Sink.ChainedDouble<Double>(sink) {
+                    // true if cancellationRequested() has been called
+                    boolean cancellationRequestedCalled;
+
+                    // cache the consumer to avoid creation on every accepted element
+                    DoubleConsumer downstreamAsDouble = downstream::accept;
+
                     @Override
                     public void begin(long size) {
                         downstream.begin(-1);
@@ -273,11 +278,27 @@
                     @Override
                     public void accept(double t) {
                         try (DoubleStream result = mapper.apply(t)) {
-                            // We can do better that this too; optimize for depth=0 case and just grab spliterator and forEach it
-                            if (result != null)
-                                result.sequential().forEach(i -> downstream.accept(i));
+                            if (result != null) {
+                                if (!cancellationRequestedCalled) {
+                                    result.sequential().forEach(downstreamAsDouble);
+                                }
+                                else {
+                                    var s = result.sequential().spliterator();
+                                    do { } while (!downstream.cancellationRequested() && s.tryAdvance(downstreamAsDouble));
+                                }
+                            }
                         }
                     }
+
+                    @Override
+                    public boolean cancellationRequested() {
+                        // If this method is called then an operation within the stream
+                        // pipeline is short-circuiting (see AbstractPipeline.copyInto).
+                        // Note that we cannot differentiate between an upstream or
+                        // downstream operation
+                        cancellationRequestedCalled = true;
+                        return downstream.cancellationRequested();
+                    }
                 };
             }
         };
--- a/src/java.base/share/classes/java/util/stream/IntPipeline.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.base/share/classes/java/util/stream/IntPipeline.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2017, 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
@@ -298,6 +298,12 @@
             @Override
             Sink<Integer> opWrapSink(int flags, Sink<Integer> sink) {
                 return new Sink.ChainedInt<Integer>(sink) {
+                    // true if cancellationRequested() has been called
+                    boolean cancellationRequestedCalled;
+
+                    // cache the consumer to avoid creation on every accepted element
+                    IntConsumer downstreamAsInt = downstream::accept;
+
                     @Override
                     public void begin(long size) {
                         downstream.begin(-1);
@@ -306,11 +312,27 @@
                     @Override
                     public void accept(int t) {
                         try (IntStream result = mapper.apply(t)) {
-                            // We can do better that this too; optimize for depth=0 case and just grab spliterator and forEach it
-                            if (result != null)
-                                result.sequential().forEach(i -> downstream.accept(i));
+                            if (result != null) {
+                                if (!cancellationRequestedCalled) {
+                                    result.sequential().forEach(downstreamAsInt);
+                                }
+                                else {
+                                    var s = result.sequential().spliterator();
+                                    do { } while (!downstream.cancellationRequested() && s.tryAdvance(downstreamAsInt));
+                                }
+                            }
                         }
                     }
+
+                    @Override
+                    public boolean cancellationRequested() {
+                        // If this method is called then an operation within the stream
+                        // pipeline is short-circuiting (see AbstractPipeline.copyInto).
+                        // Note that we cannot differentiate between an upstream or
+                        // downstream operation
+                        cancellationRequestedCalled = true;
+                        return downstream.cancellationRequested();
+                    }
                 };
             }
         };
--- a/src/java.base/share/classes/java/util/stream/LongPipeline.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.base/share/classes/java/util/stream/LongPipeline.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2017, 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
@@ -280,6 +280,12 @@
             @Override
             Sink<Long> opWrapSink(int flags, Sink<Long> sink) {
                 return new Sink.ChainedLong<Long>(sink) {
+                    // true if cancellationRequested() has been called
+                    boolean cancellationRequestedCalled;
+
+                    // cache the consumer to avoid creation on every accepted element
+                    LongConsumer downstreamAsLong = downstream::accept;
+
                     @Override
                     public void begin(long size) {
                         downstream.begin(-1);
@@ -288,11 +294,27 @@
                     @Override
                     public void accept(long t) {
                         try (LongStream result = mapper.apply(t)) {
-                            // We can do better that this too; optimize for depth=0 case and just grab spliterator and forEach it
-                            if (result != null)
-                                result.sequential().forEach(i -> downstream.accept(i));
+                            if (result != null) {
+                                if (!cancellationRequestedCalled) {
+                                    result.sequential().forEach(downstreamAsLong);
+                                }
+                                else {
+                                    var s = result.sequential().spliterator();
+                                    do { } while (!downstream.cancellationRequested() && s.tryAdvance(downstreamAsLong));
+                                }
+                            }
                         }
                     }
+
+                    @Override
+                    public boolean cancellationRequested() {
+                        // If this method is called then an operation within the stream
+                        // pipeline is short-circuiting (see AbstractPipeline.copyInto).
+                        // Note that we cannot differentiate between an upstream or
+                        // downstream operation
+                        cancellationRequestedCalled = true;
+                        return downstream.cancellationRequested();
+                    }
                 };
             }
         };
--- a/src/java.base/share/classes/java/util/stream/ReferencePipeline.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.base/share/classes/java/util/stream/ReferencePipeline.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2017, 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
@@ -253,12 +253,14 @@
     @Override
     public final <R> Stream<R> flatMap(Function<? super P_OUT, ? extends Stream<? extends R>> mapper) {
         Objects.requireNonNull(mapper);
-        // We can do better than this, by polling cancellationRequested when stream is infinite
         return new StatelessOp<P_OUT, R>(this, StreamShape.REFERENCE,
                                      StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT | StreamOpFlag.NOT_SIZED) {
             @Override
             Sink<P_OUT> opWrapSink(int flags, Sink<R> sink) {
                 return new Sink.ChainedReference<P_OUT, R>(sink) {
+                    // true if cancellationRequested() has been called
+                    boolean cancellationRequestedCalled;
+
                     @Override
                     public void begin(long size) {
                         downstream.begin(-1);
@@ -267,11 +269,27 @@
                     @Override
                     public void accept(P_OUT u) {
                         try (Stream<? extends R> result = mapper.apply(u)) {
-                            // We can do better that this too; optimize for depth=0 case and just grab spliterator and forEach it
-                            if (result != null)
-                                result.sequential().forEach(downstream);
+                            if (result != null) {
+                                if (!cancellationRequestedCalled) {
+                                    result.sequential().forEach(downstream);
+                                }
+                                else {
+                                    var s = result.sequential().spliterator();
+                                    do { } while (!downstream.cancellationRequested() && s.tryAdvance(downstream));
+                                }
+                            }
                         }
                     }
+
+                    @Override
+                    public boolean cancellationRequested() {
+                        // If this method is called then an operation within the stream
+                        // pipeline is short-circuiting (see AbstractPipeline.copyInto).
+                        // Note that we cannot differentiate between an upstream or
+                        // downstream operation
+                        cancellationRequestedCalled = true;
+                        return downstream.cancellationRequested();
+                    }
                 };
             }
         };
@@ -280,13 +298,17 @@
     @Override
     public final IntStream flatMapToInt(Function<? super P_OUT, ? extends IntStream> mapper) {
         Objects.requireNonNull(mapper);
-        // We can do better than this, by polling cancellationRequested when stream is infinite
         return new IntPipeline.StatelessOp<P_OUT>(this, StreamShape.REFERENCE,
                                               StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT | StreamOpFlag.NOT_SIZED) {
             @Override
             Sink<P_OUT> opWrapSink(int flags, Sink<Integer> sink) {
                 return new Sink.ChainedReference<P_OUT, Integer>(sink) {
+                    // true if cancellationRequested() has been called
+                    boolean cancellationRequestedCalled;
+
+                    // cache the consumer to avoid creation on every accepted element
                     IntConsumer downstreamAsInt = downstream::accept;
+
                     @Override
                     public void begin(long size) {
                         downstream.begin(-1);
@@ -295,11 +317,23 @@
                     @Override
                     public void accept(P_OUT u) {
                         try (IntStream result = mapper.apply(u)) {
-                            // We can do better that this too; optimize for depth=0 case and just grab spliterator and forEach it
-                            if (result != null)
-                                result.sequential().forEach(downstreamAsInt);
+                            if (result != null) {
+                                if (!cancellationRequestedCalled) {
+                                    result.sequential().forEach(downstreamAsInt);
+                                }
+                                else {
+                                    var s = result.sequential().spliterator();
+                                    do { } while (!downstream.cancellationRequested() && s.tryAdvance(downstreamAsInt));
+                                }
+                            }
                         }
                     }
+
+                    @Override
+                    public boolean cancellationRequested() {
+                        cancellationRequestedCalled = true;
+                        return downstream.cancellationRequested();
+                    }
                 };
             }
         };
@@ -308,13 +342,17 @@
     @Override
     public final DoubleStream flatMapToDouble(Function<? super P_OUT, ? extends DoubleStream> mapper) {
         Objects.requireNonNull(mapper);
-        // We can do better than this, by polling cancellationRequested when stream is infinite
         return new DoublePipeline.StatelessOp<P_OUT>(this, StreamShape.REFERENCE,
                                                      StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT | StreamOpFlag.NOT_SIZED) {
             @Override
             Sink<P_OUT> opWrapSink(int flags, Sink<Double> sink) {
                 return new Sink.ChainedReference<P_OUT, Double>(sink) {
+                    // true if cancellationRequested() has been called
+                    boolean cancellationRequestedCalled;
+
+                    // cache the consumer to avoid creation on every accepted element
                     DoubleConsumer downstreamAsDouble = downstream::accept;
+
                     @Override
                     public void begin(long size) {
                         downstream.begin(-1);
@@ -323,11 +361,23 @@
                     @Override
                     public void accept(P_OUT u) {
                         try (DoubleStream result = mapper.apply(u)) {
-                            // We can do better that this too; optimize for depth=0 case and just grab spliterator and forEach it
-                            if (result != null)
-                                result.sequential().forEach(downstreamAsDouble);
+                            if (result != null) {
+                                if (!cancellationRequestedCalled) {
+                                    result.sequential().forEach(downstreamAsDouble);
+                                }
+                                else {
+                                    var s = result.sequential().spliterator();
+                                    do { } while (!downstream.cancellationRequested() && s.tryAdvance(downstreamAsDouble));
+                                }
+                            }
                         }
                     }
+
+                    @Override
+                    public boolean cancellationRequested() {
+                        cancellationRequestedCalled = true;
+                        return downstream.cancellationRequested();
+                    }
                 };
             }
         };
@@ -342,7 +392,12 @@
             @Override
             Sink<P_OUT> opWrapSink(int flags, Sink<Long> sink) {
                 return new Sink.ChainedReference<P_OUT, Long>(sink) {
+                    // true if cancellationRequested() has been called
+                    boolean cancellationRequestedCalled;
+
+                    // cache the consumer to avoid creation on every accepted element
                     LongConsumer downstreamAsLong = downstream::accept;
+
                     @Override
                     public void begin(long size) {
                         downstream.begin(-1);
@@ -351,11 +406,23 @@
                     @Override
                     public void accept(P_OUT u) {
                         try (LongStream result = mapper.apply(u)) {
-                            // We can do better that this too; optimize for depth=0 case and just grab spliterator and forEach it
-                            if (result != null)
-                                result.sequential().forEach(downstreamAsLong);
+                            if (result != null) {
+                                if (!cancellationRequestedCalled) {
+                                    result.sequential().forEach(downstreamAsLong);
+                                }
+                                else {
+                                    var s = result.sequential().spliterator();
+                                    do { } while (!downstream.cancellationRequested() && s.tryAdvance(downstreamAsLong));
+                                }
+                            }
                         }
                     }
+
+                    @Override
+                    public boolean cancellationRequested() {
+                        cancellationRequestedCalled = true;
+                        return downstream.cancellationRequested();
+                    }
                 };
             }
         };
--- a/src/java.base/share/classes/java/util/stream/SortedOps.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.base/share/classes/java/util/stream/SortedOps.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2017, 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
@@ -304,7 +304,8 @@
     private abstract static class AbstractRefSortingSink<T> extends Sink.ChainedReference<T, T> {
         protected final Comparator<? super T> comparator;
         // @@@ could be a lazy final value, if/when support is added
-        protected boolean cancellationWasRequested;
+        // true if cancellationRequested() has been called
+        protected boolean cancellationRequestedCalled;
 
         AbstractRefSortingSink(Sink<? super T> downstream, Comparator<? super T> comparator) {
             super(downstream);
@@ -319,7 +320,11 @@
          */
         @Override
         public final boolean cancellationRequested() {
-            cancellationWasRequested = true;
+            // If this method is called then an operation within the stream
+            // pipeline is short-circuiting (see AbstractPipeline.copyInto).
+            // Note that we cannot differentiate between an upstream or
+            // downstream operation
+            cancellationRequestedCalled = true;
             return false;
         }
     }
@@ -347,7 +352,7 @@
         public void end() {
             Arrays.sort(array, 0, offset, comparator);
             downstream.begin(offset);
-            if (!cancellationWasRequested) {
+            if (!cancellationRequestedCalled) {
                 for (int i = 0; i < offset; i++)
                     downstream.accept(array[i]);
             }
@@ -386,7 +391,7 @@
         public void end() {
             list.sort(comparator);
             downstream.begin(list.size());
-            if (!cancellationWasRequested) {
+            if (!cancellationRequestedCalled) {
                 list.forEach(downstream::accept);
             }
             else {
@@ -409,7 +414,8 @@
      * Abstract {@link Sink} for implementing sort on int streams.
      */
     private abstract static class AbstractIntSortingSink extends Sink.ChainedInt<Integer> {
-        protected boolean cancellationWasRequested;
+        // true if cancellationRequested() has been called
+        protected boolean cancellationRequestedCalled;
 
         AbstractIntSortingSink(Sink<? super Integer> downstream) {
             super(downstream);
@@ -417,7 +423,7 @@
 
         @Override
         public final boolean cancellationRequested() {
-            cancellationWasRequested = true;
+            cancellationRequestedCalled = true;
             return false;
         }
     }
@@ -444,7 +450,7 @@
         public void end() {
             Arrays.sort(array, 0, offset);
             downstream.begin(offset);
-            if (!cancellationWasRequested) {
+            if (!cancellationRequestedCalled) {
                 for (int i = 0; i < offset; i++)
                     downstream.accept(array[i]);
             }
@@ -484,7 +490,7 @@
             int[] ints = b.asPrimitiveArray();
             Arrays.sort(ints);
             downstream.begin(ints.length);
-            if (!cancellationWasRequested) {
+            if (!cancellationRequestedCalled) {
                 for (int anInt : ints)
                     downstream.accept(anInt);
             }
@@ -507,7 +513,8 @@
      * Abstract {@link Sink} for implementing sort on long streams.
      */
     private abstract static class AbstractLongSortingSink extends Sink.ChainedLong<Long> {
-        protected boolean cancellationWasRequested;
+        // true if cancellationRequested() has been called
+        protected boolean cancellationRequestedCalled;
 
         AbstractLongSortingSink(Sink<? super Long> downstream) {
             super(downstream);
@@ -515,7 +522,7 @@
 
         @Override
         public final boolean cancellationRequested() {
-            cancellationWasRequested = true;
+            cancellationRequestedCalled = true;
             return false;
         }
     }
@@ -542,7 +549,7 @@
         public void end() {
             Arrays.sort(array, 0, offset);
             downstream.begin(offset);
-            if (!cancellationWasRequested) {
+            if (!cancellationRequestedCalled) {
                 for (int i = 0; i < offset; i++)
                     downstream.accept(array[i]);
             }
@@ -582,7 +589,7 @@
             long[] longs = b.asPrimitiveArray();
             Arrays.sort(longs);
             downstream.begin(longs.length);
-            if (!cancellationWasRequested) {
+            if (!cancellationRequestedCalled) {
                 for (long aLong : longs)
                     downstream.accept(aLong);
             }
@@ -605,7 +612,8 @@
      * Abstract {@link Sink} for implementing sort on long streams.
      */
     private abstract static class AbstractDoubleSortingSink extends Sink.ChainedDouble<Double> {
-        protected boolean cancellationWasRequested;
+        // true if cancellationRequested() has been called
+        protected boolean cancellationRequestedCalled;
 
         AbstractDoubleSortingSink(Sink<? super Double> downstream) {
             super(downstream);
@@ -613,7 +621,7 @@
 
         @Override
         public final boolean cancellationRequested() {
-            cancellationWasRequested = true;
+            cancellationRequestedCalled = true;
             return false;
         }
     }
@@ -640,7 +648,7 @@
         public void end() {
             Arrays.sort(array, 0, offset);
             downstream.begin(offset);
-            if (!cancellationWasRequested) {
+            if (!cancellationRequestedCalled) {
                 for (int i = 0; i < offset; i++)
                     downstream.accept(array[i]);
             }
@@ -680,7 +688,7 @@
             double[] doubles = b.asPrimitiveArray();
             Arrays.sort(doubles);
             downstream.begin(doubles.length);
-            if (!cancellationWasRequested) {
+            if (!cancellationRequestedCalled) {
                 for (double aDouble : doubles)
                     downstream.accept(aDouble);
             }
--- a/src/java.base/share/classes/module-info.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.base/share/classes/module-info.java	Fri Jan 19 09:32:10 2018 -0800
@@ -212,7 +212,8 @@
     exports jdk.internal.util.jar to
         jdk.jartool;
     exports sun.net to
-        jdk.incubator.httpclient;
+        jdk.incubator.httpclient,
+        jdk.naming.dns;
     exports sun.net.ext to
         jdk.net;
     exports sun.net.dns to
--- a/src/java.base/share/classes/sun/security/rsa/RSAPublicKeyImpl.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.base/share/classes/sun/security/rsa/RSAPublicKeyImpl.java	Fri Jan 19 09:32:10 2018 -0800
@@ -48,6 +48,7 @@
 public final class RSAPublicKeyImpl extends X509Key implements RSAPublicKey {
 
     private static final long serialVersionUID = 2644735423591199609L;
+    private static final BigInteger THREE = BigInteger.valueOf(3);
 
     private BigInteger n;       // modulus
     private BigInteger e;       // public exponent
@@ -61,6 +62,7 @@
         this.n = n;
         this.e = e;
         RSAKeyFactory.checkRSAProviderKeyLengths(n.bitLength(), e);
+        checkExponentRange();
         // generate the encoding
         algid = RSAPrivateCrtKeyImpl.rsaId;
         try {
@@ -83,6 +85,19 @@
     public RSAPublicKeyImpl(byte[] encoded) throws InvalidKeyException {
         decode(encoded);
         RSAKeyFactory.checkRSAProviderKeyLengths(n.bitLength(), e);
+        checkExponentRange();
+    }
+
+    private void checkExponentRange() throws InvalidKeyException {
+        // the exponent should be smaller than the modulus
+        if (e.compareTo(n) >= 0) {
+            throw new InvalidKeyException("exponent is larger than modulus");
+        }
+
+        // the exponent should be at least 3
+        if (e.compareTo(THREE) < 0) {
+            throw new InvalidKeyException("exponent is smaller than 3");
+        }
     }
 
     // see JCA doc
--- a/src/java.base/share/classes/sun/security/tools/keytool/Main.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.base/share/classes/sun/security/tools/keytool/Main.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1806,8 +1806,7 @@
             } else if ("RSA".equalsIgnoreCase(keyAlgName)) {
                 keysize = SecurityProviderConstants.DEF_RSA_KEY_SIZE;
             } else if ("DSA".equalsIgnoreCase(keyAlgName)) {
-                // hardcode for now as DEF_DSA_KEY_SIZE is still 1024
-                keysize = 2048; // SecurityProviderConstants.DEF_DSA_KEY_SIZE;
+                keysize = SecurityProviderConstants.DEF_DSA_KEY_SIZE;
             }
         }
 
--- a/src/java.base/share/classes/sun/security/util/DerValue.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.base/share/classes/sun/security/util/DerValue.java	Fri Jan 19 09:32:10 2018 -0800
@@ -490,20 +490,27 @@
      * @return the octet string held in this DER value
      */
     public byte[] getOctetString() throws IOException {
-        byte[] bytes;
 
         if (tag != tag_OctetString && !isConstructed(tag_OctetString)) {
             throw new IOException(
                 "DerValue.getOctetString, not an Octet String: " + tag);
         }
-        bytes = new byte[length];
-        // Note: do not tempt to call buffer.read(bytes) at all. There's a
+        // Note: do not attempt to call buffer.read(bytes) at all. There's a
         // known bug that it returns -1 instead of 0.
         if (length == 0) {
-            return bytes;
+            return new byte[0];
         }
-        if (buffer.read(bytes) != length)
+
+        // Only allocate the array if there are enough bytes available.
+        // This only works for ByteArrayInputStream.
+        // The assignment below ensures that buffer has the required type.
+        ByteArrayInputStream arrayInput = buffer;
+        if (arrayInput.available() < length) {
             throw new IOException("short read on DerValue buffer");
+        }
+        byte[] bytes = new byte[length];
+        arrayInput.read(bytes);
+
         if (isConstructed()) {
             DerInputStream in = new DerInputStream(bytes, 0, bytes.length,
                 buffer.allowBER);
--- a/src/java.base/share/classes/sun/security/util/SecurityProviderConstants.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.base/share/classes/sun/security/util/SecurityProviderConstants.java	Fri Jan 19 09:32:10 2018 -0800
@@ -64,7 +64,7 @@
     static {
         String keyLengthStr = GetPropertyAction.privilegedGetProperty
             (KEY_LENGTH_PROP);
-        int dsaKeySize = 1024;
+        int dsaKeySize = 2048;
         int rsaKeySize = 2048;
         int dhKeySize = 2048;
         int ecKeySize = 256;
--- a/src/java.base/share/conf/security/java.security	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.base/share/conf/security/java.security	Fri Jan 19 09:32:10 2018 -0800
@@ -676,7 +676,7 @@
 # Example:
 #   jdk.tls.disabledAlgorithms=MD5, SSLv3, DSA, RSA keySize < 2048
 jdk.tls.disabledAlgorithms=SSLv3, RC4, MD5withRSA, DH keySize < 1024, \
-    EC keySize < 224
+    EC keySize < 224, DES40_CBC, RC4_40
 
 #
 # Legacy algorithms for Secure Socket Layer/Transport Layer Security (SSL/TLS)
@@ -737,8 +737,6 @@
 #
 jdk.tls.legacyAlgorithms= \
         K_NULL, C_NULL, M_NULL, \
-        DHE_DSS_EXPORT, DHE_RSA_EXPORT, DH_anon_EXPORT, DH_DSS_EXPORT, \
-        DH_RSA_EXPORT, RSA_EXPORT, \
         DH_anon, ECDH_anon, \
         RC4_128, RC4_40, DES_CBC, DES40_CBC, \
         3DES_EDE_CBC
@@ -814,14 +812,14 @@
 #     limited:    These policy files contain more restricted cryptographic
 #                 strengths
 #
-# The default setting is determined by the value of the “crypto.policy”
+# The default setting is determined by the value of the "crypto.policy"
 # Security property below. If your country or usage requires the
-# traditional restrictive policy, the “limited” Java cryptographic
+# traditional restrictive policy, the "limited" Java cryptographic
 # policy is still available and may be appropriate for your environment.
 #
 # If you have restrictions that do not fit either use case mentioned
 # above, Java provides the capability to customize these policy files.
-# The “crypto.policy” security property points to a subdirectory
+# The "crypto.policy" security property points to a subdirectory
 # within <java-home>/conf/security/policy/ which can be customized.
 # Please see the <java-home>/conf/security/policy/README.txt file or consult
 # the Java Security Guide/JCA documentation for more information.
@@ -985,3 +983,24 @@
 #    java.rmi.dgc.VMID;\
 #    java.rmi.dgc.Lease;\
 #    maxdepth=5;maxarray=10000
+
+# CORBA ORBIorTypeCheckRegistryFilter
+# Type check enhancement for ORB::string_to_object processing
+#
+# An IOR type check filter, if configured, is used by an ORB during
+# an ORB::string_to_object invocation to check the veracity of the type encoded
+# in the ior string. 
+#
+# The filter pattern consists of a semi-colon separated list of class names.
+# The configured list contains the binary class names of the IDL interface types 
+# corresponding to the IDL stub class to be instantiated.
+# As such, a filter specifies a list of IDL stub classes that will be
+# allowed by an ORB when an ORB::string_to_object is invoked.
+# It is used to specify a white list configuration of acceptable
+# IDL stub types which may be contained in a stringified IOR
+# parameter passed as input to an ORB::string_to_object method.
+#
+# Note: This property is currently used by the JDK Reference implementation.
+# It is not guaranteed to be examined and used by other implementations.
+#
+#com.sun.CORBA.ORBIorTypeCheckRegistryFilter=binary_class_name;binary_class_name
--- a/src/java.base/share/conf/security/policy/README.txt	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.base/share/conf/security/policy/README.txt	Fri Jan 19 09:32:10 2018 -0800
@@ -8,7 +8,7 @@
 Import and export control rules on cryptographic software vary from
 country to country.  The Java Cryptography Extension (JCE) architecture
 allows flexible cryptographic key strength to be configured via the
-jurisdiction policy files which are referenced by the “crypto.policy”
+jurisdiction policy files which are referenced by the "crypto.policy"
 security property in the <java-home>/conf/security/java.security file.
 
 By default, Java provides two different sets of cryptographic policy
@@ -20,8 +20,8 @@
     limited:    These policy files contain more restricted cryptographic
                 strengths
 
-These files reside in <java-home>/conf/security/policy in the “unlimited”
-or “limited” subdirectories respectively.
+These files reside in <java-home>/conf/security/policy in the "unlimited"
+or "limited" subdirectories respectively.
 
 Each subdirectory contains a complete policy configuration,
 and subdirectories can be added/edited/removed to reflect your
--- a/src/java.base/share/lib/security/default.policy	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.base/share/lib/security/default.policy	Fri Jan 19 09:32:10 2018 -0800
@@ -124,6 +124,7 @@
     permission java.util.PropertyPermission "sun.security.pkcs11.allowSingleThreadedModules", "read";
     permission java.util.PropertyPermission "os.name", "read";
     permission java.util.PropertyPermission "os.arch", "read";
+    permission java.util.PropertyPermission "jdk.crypto.KeyAgreement.legacyKDF", "read";
     permission java.security.SecurityPermission "putProviderProperty.*";
     permission java.security.SecurityPermission "clearProviderProperties.*";
     permission java.security.SecurityPermission "removeProviderProperty.*";
--- a/src/java.base/share/native/libjava/System.c	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.base/share/native/libjava/System.c	Fri Jan 19 09:32:10 2018 -0800
@@ -108,9 +108,14 @@
         (*env)->DeleteLocalRef(env, jkey);                            \
     } else ((void) 0)
 
-#ifndef VENDOR /* Third party may overwrite this. */
+/* Third party may overwrite these values. */
+#ifndef VENDOR
 #define VENDOR "Oracle Corporation"
+#endif
+#ifndef VENDOR_URL
 #define VENDOR_URL "http://java.oracle.com/"
+#endif
+#ifndef VENDOR_URL_BUG
 #define VENDOR_URL_BUG "http://bugreport.java.com/bugreport/"
 #endif
 
--- a/src/java.base/share/native/libjimage/imageFile.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.base/share/native/libjimage/imageFile.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -205,12 +205,19 @@
 // Manage a table of open image files.  This table allows multiple access points
 // to share an open image.
 ImageFileReaderTable::ImageFileReaderTable() : _count(0), _max(_growth) {
-    _table = new ImageFileReader*[_max];
+    _table = static_cast<ImageFileReader**>(calloc(_max, sizeof(ImageFileReader*)));
     assert(_table != NULL && "allocation failed");
 }
 
 ImageFileReaderTable::~ImageFileReaderTable() {
-    delete[] _table;
+    for (u4 i = 0; i < _count; i++) {
+        ImageFileReader* image = _table[i];
+
+        if (image != NULL) {
+            delete image;
+        }
+    }
+    free(_table);
 }
 
 // Add a new image entry to the table.
--- a/src/java.base/share/native/libjimage/imageFile.hpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.base/share/native/libjimage/imageFile.hpp	Fri Jan 19 09:32:10 2018 -0800
@@ -402,6 +402,7 @@
 // 'opened' by reference point and decremented when 'closed'.    Use of zero
 // leads the ImageFileReader to be actually closed and discarded.
 class ImageFileReader {
+friend class ImageFileReaderTable;
 private:
     // Manage a number of image files such that an image can be shared across
     // multiple uses (ex. loader.)
--- a/src/java.compiler/share/classes/javax/lang/model/element/ElementVisitor.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.compiler/share/classes/javax/lang/model/element/ElementVisitor.java	Fri Jan 19 09:32:10 2018 -0800
@@ -152,8 +152,8 @@
     /**
      * Visits a module element.
      *
-     * @implSpec Visits a {@code ModuleElement} by calling {@code
-     * visitUnknown(e, p)}.
+     * @implSpec The default implementation visits a {@code
+     * ModuleElement} by calling {@code visitUnknown(e, p)}.
      *
      * @param e  the element to visit
      * @param p  a visitor-specified parameter
--- a/src/java.compiler/share/classes/javax/lang/model/element/ModuleElement.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.compiler/share/classes/javax/lang/model/element/ModuleElement.java	Fri Jan 19 09:32:10 2018 -0800
@@ -201,11 +201,10 @@
          * Visits any directive as if by passing itself to that
          * directive's {@link Directive#accept accept} method and passing
          * {@code null} for the additional parameter.
-         * The invocation {@code v.visit(d)} is equivalent to
-         * {@code d.accept(v, null)}.
+         *
          * @param d  the directive to visit
          * @return a visitor-specified result
-         * @implSpec This implementation is {@code visit(d, null)}
+         * @implSpec The default implementation is {@code d.accept(v, null)}.
          */
         default R visit(Directive d) {
             return d.accept(this, null);
@@ -214,11 +213,11 @@
         /**
          * Visits any directive as if by passing itself to that
          * directive's {@link Directive#accept accept} method.
-         * The invocation {@code v.visit(d, p)} is equivalent to
-         * {@code d.accept(v, p)}.
+         *
          * @param d  the directive to visit
          * @param p  a visitor-specified parameter
          * @return a visitor-specified result
+         * @implSpec The default implementation is {@code d.accept(v, p)}.
          */
         default R visit(Directive d, P p) {
             return d.accept(this, p);
@@ -271,7 +270,7 @@
          * @param p  a visitor-specified parameter
          * @return a visitor-specified result
          * @throws UnknownDirectiveException a visitor implementation may optionally throw this exception
-         * @implSpec This implementation throws {@code new UnknownDirectiveException(d, p)}.
+         * @implSpec The default implementation throws {@code new UnknownDirectiveException(d, p)}.
          */
         default R visitUnknown(Directive d, P p) {
             throw new UnknownDirectiveException(d, p);
--- a/src/java.corba/share/classes/com/sun/corba/se/impl/encoding/BufferManagerWriteGrow.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.corba/share/classes/com/sun/corba/se/impl/encoding/BufferManagerWriteGrow.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2003, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2017, 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
@@ -26,11 +26,13 @@
 package com.sun.corba.se.impl.encoding;
 
 import com.sun.corba.se.impl.orbutil.ORBConstants;
+import com.sun.corba.se.impl.orbutil.ORBUtility;
 import com.sun.corba.se.impl.encoding.ByteBufferWithInfo;
 import com.sun.corba.se.impl.encoding.BufferManagerWrite;
 import com.sun.corba.se.pept.encoding.OutputObject;
 import com.sun.corba.se.pept.transport.Connection;
 import com.sun.corba.se.spi.orb.ORB;
+import com.sun.corba.se.spi.orb.ORBData;
 
 public class BufferManagerWriteGrow extends BufferManagerWrite
 {
@@ -48,7 +50,20 @@
      * buffer manager as set in the ORB.
      */
     public int getBufferSize() {
-        return orb.getORBData().getGIOPBufferSize();
+        ORBData orbData = null;
+        int bufferSize = ORBConstants.GIOP_DEFAULT_BUFFER_SIZE;
+        if (orb != null) {
+            orbData = orb.getORBData();
+            if (orbData != null) {
+                bufferSize = orbData.getGIOPBufferSize();
+                dprint("BufferManagerWriteGrow.getBufferSize: bufferSize == " + bufferSize);
+            } else {
+                dprint("BufferManagerWriteGrow.getBufferSize: orbData reference is NULL");
+            }
+        } else {
+            dprint("BufferManagerWriteGrow.getBufferSize: orb reference is NULL");
+        }
+        return bufferSize;
     }
 
     public void overflow (ByteBufferWithInfo bbwi)
@@ -89,4 +104,9 @@
      */
     public void close() {}
 
+    private void dprint(String msg) {
+        if (orb.transportDebugFlag) {
+            ORBUtility.dprint(this, msg);
 }
+    }
+}
--- a/src/java.corba/share/classes/com/sun/corba/se/impl/encoding/CDRInputStream_1_0.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.corba/share/classes/com/sun/corba/se/impl/encoding/CDRInputStream_1_0.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, 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
@@ -725,12 +725,14 @@
     //    IDLEntity.class.isAssignableFrom( clz ).
     // 3. If clz is an interface, use it to create the appropriate
     //    stub factory.
+
     public org.omg.CORBA.Object read_Object(Class clz)
     {
         // In any case, we must first read the IOR.
         IOR ior = IORFactories.makeIOR(parent) ;
-        if (ior.isNil())
+        if (ior.isNil()) {
             return null ;
+        }
 
         PresentationManager.StubFactoryFactory sff = ORB.getStubFactoryFactory() ;
         String codeBase = ior.getProfile().getCodebase() ;
@@ -739,6 +741,7 @@
         if (clz == null) {
             RepositoryId rid = RepositoryId.cache.getId( ior.getTypeId() ) ;
             String className = rid.getClassName() ;
+            orb.validateIORClass(className);
             boolean isIDLInterface = rid.isIDLType() ;
 
             if (className == null || className.equals( "" ))
@@ -761,11 +764,9 @@
         } else {
             // clz is an interface class
             boolean isIDL = IDLEntity.class.isAssignableFrom( clz ) ;
-
             stubFactory = sff.createStubFactory( clz.getName(),
                 isIDL, codeBase, clz, clz.getClassLoader() ) ;
         }
-
         return internalIORToObject( ior, stubFactory, orb ) ;
     }
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/java.corba/share/classes/com/sun/corba/se/impl/ior/IORTypeCheckRegistryImpl.java	Fri Jan 19 09:32:10 2018 -0800
@@ -0,0 +1,179 @@
+/*
+ * Copyright (c) 2017, 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.corba.se.impl.ior;
+
+import java.util.Set;
+
+import com.sun.corba.se.impl.orbutil.ORBUtility;
+import com.sun.corba.se.spi.ior.IORTypeCheckRegistry;
+import com.sun.corba.se.spi.orb.ORB;
+
+public class IORTypeCheckRegistryImpl implements IORTypeCheckRegistry {
+
+    private final Set<String> iorTypeNames;
+    private static final Set<String> builtinIorTypeNames;
+    private ORB theOrb;
+
+    static {
+        builtinIorTypeNames = initBuiltinIorTypeNames();
+    }
+
+    public IORTypeCheckRegistryImpl( String filterProperties, ORB orb) {
+        theOrb = orb;
+        iorTypeNames = parseIorClassNameList(filterProperties);
+    }
+
+    /*
+     *
+     * A note on the validation flow:
+     * 1. against the filter class name list
+     * 2. against the builtin class name list
+     */
+
+    @Override
+    public boolean isValidIORType(String iorClassName) {
+        dprintTransport(".isValidIORType : iorClassName == " + iorClassName);
+        return validateIorTypeByName(iorClassName);
+    }
+
+
+    private boolean validateIorTypeByName(String iorClassName) {
+        dprintTransport(".validateIorTypeByName : iorClassName == " + iorClassName);
+        boolean isValidType;
+
+        isValidType = checkIorTypeNames(iorClassName);
+
+        if (!isValidType) {
+            isValidType = checkBuiltinClassNames(iorClassName);
+        }
+
+        dprintTransport(".validateIorTypeByName : isValidType == " + isValidType);
+        return isValidType;
+    }
+
+
+    /*
+     * check if the class name corresponding to an IOR Type name
+     * is in the ior class name list as generated from the filter property.
+     * So if the IOR type is recorded in the registry then allow the creation of the
+     * stub factory and let it resolve and load the class. That is if current
+     * type check deliberation permits.
+     * IOR Type names are configured by the filter property
+     */
+
+    private boolean checkIorTypeNames(
+            String theIorClassName) {
+        return (iorTypeNames != null) && (iorTypeNames.contains(theIorClassName));
+    }
+
+    /*
+     * Check the IOR interface class name against the set of
+     * class names that correspond to the builtin JDK IDL stub classes.
+     */
+
+    private boolean  checkBuiltinClassNames(
+            String theIorClassName) {
+        return builtinIorTypeNames.contains(theIorClassName);
+    }
+
+
+    private Set<String> parseIorClassNameList(String filterProperty) {
+        Set<String> _iorTypeNames = null;
+        if (filterProperty != null) {
+            String[] tempIorClassNames = filterProperty.split(";");
+            _iorTypeNames = Set.<String>of(tempIorClassNames);
+            if (theOrb.orbInitDebugFlag) {
+                dprintConfiguredIorTypeNames();
+            }
+        }
+        return _iorTypeNames;
+    }
+
+
+    private static Set<String> initBuiltinIorTypeNames() {
+        Set<Class<?>> builtInCorbaStubTypes = initBuiltInCorbaStubTypes();
+        String [] tempBuiltinIorTypeNames = new String[builtInCorbaStubTypes.size()];
+        int i = 0;
+        for (Class<?> _stubClass: builtInCorbaStubTypes) {
+            tempBuiltinIorTypeNames[i++] = _stubClass.getName();
+        }
+        return  Set.<String>of(tempBuiltinIorTypeNames);
+    }
+
+    private static Set<Class<?>> initBuiltInCorbaStubTypes() {
+        Class<?> tempBuiltinCorbaStubTypes[] = {
+                com.sun.corba.se.spi.activation.Activator.class,
+                com.sun.corba.se.spi.activation._ActivatorStub.class,
+                com.sun.corba.se.spi.activation._InitialNameServiceStub.class,
+                com.sun.corba.se.spi.activation._LocatorStub.class,
+                com.sun.corba.se.spi.activation._RepositoryStub.class,
+                com.sun.corba.se.spi.activation._ServerManagerStub.class,
+                com.sun.corba.se.spi.activation._ServerStub.class,
+                org.omg.CosNaming.BindingIterator.class,
+                org.omg.CosNaming._BindingIteratorStub.class,
+                org.omg.CosNaming.NamingContextExt.class,
+                org.omg.CosNaming._NamingContextExtStub.class,
+                org.omg.CosNaming.NamingContext.class,
+                org.omg.CosNaming._NamingContextStub.class,
+                org.omg.DynamicAny.DynAnyFactory.class,
+                org.omg.DynamicAny._DynAnyFactoryStub.class,
+                org.omg.DynamicAny.DynAny.class,
+                org.omg.DynamicAny._DynAnyStub.class,
+                org.omg.DynamicAny.DynArray.class,
+                org.omg.DynamicAny._DynArrayStub.class,
+                org.omg.DynamicAny.DynEnum.class,
+                org.omg.DynamicAny._DynEnumStub.class,
+                org.omg.DynamicAny.DynFixed.class,
+                org.omg.DynamicAny._DynFixedStub.class,
+                org.omg.DynamicAny.DynSequence.class,
+                org.omg.DynamicAny._DynSequenceStub.class,
+                org.omg.DynamicAny.DynStruct.class,
+                org.omg.DynamicAny._DynStructStub.class,
+                org.omg.DynamicAny.DynUnion.class,
+                org.omg.DynamicAny._DynUnionStub.class,
+                org.omg.DynamicAny._DynValueStub.class,
+                org.omg.DynamicAny.DynValue.class,
+                org.omg.PortableServer.ServantActivator.class,
+                org.omg.PortableServer._ServantActivatorStub.class,
+                org.omg.PortableServer.ServantLocator.class,
+                org.omg.PortableServer._ServantLocatorStub.class };
+        return Set.<Class<?>>of(tempBuiltinCorbaStubTypes);
+    }
+
+    private void dprintConfiguredIorTypeNames() {
+        if (iorTypeNames != null) {
+            for (String iorTypeName : iorTypeNames) {
+                ORBUtility.dprint(this, ".dprintConfiguredIorTypeNames: " + iorTypeName);
+            }
+        }
+    }
+
+    private void dprintTransport(String msg) {
+        if (theOrb.transportDebugFlag) {
+            ORBUtility.dprint(this, msg);
+        }
+    }
+}
--- a/src/java.corba/share/classes/com/sun/corba/se/impl/orb/ORBImpl.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.corba/share/classes/com/sun/corba/se/impl/orb/ORBImpl.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2017, 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
@@ -54,6 +54,7 @@
 
 import java.security.PrivilegedAction;
 import java.security.AccessController;
+import java.security.Security;
 
 import javax.rmi.CORBA.Util;
 import javax.rmi.CORBA.ValueHandler;
@@ -90,6 +91,7 @@
 import com.sun.corba.se.pept.transport.TransportManager;
 
 import com.sun.corba.se.spi.ior.IOR;
+import com.sun.corba.se.spi.ior.IORTypeCheckRegistry;
 import com.sun.corba.se.spi.ior.IdentifiableFactoryFinder;
 import com.sun.corba.se.spi.ior.TaggedComponentFactoryFinder;
 import com.sun.corba.se.spi.ior.IORFactories;
@@ -124,6 +126,7 @@
 import com.sun.corba.se.spi.transport.CorbaContactInfoListFactory;
 import com.sun.corba.se.spi.transport.CorbaTransportManager;
 import com.sun.corba.se.spi.legacy.connection.LegacyServerSocketManager;
+import com.sun.corba.se.spi.logging.CORBALogDomains;
 import com.sun.corba.se.spi.copyobject.CopierManager;
 import com.sun.corba.se.spi.presentation.rmi.PresentationDefaults;
 import com.sun.corba.se.spi.presentation.rmi.PresentationManager;
@@ -145,6 +148,7 @@
 import com.sun.corba.se.impl.encoding.CachedCodeBase;
 import com.sun.corba.se.impl.interceptors.PIHandlerImpl;
 import com.sun.corba.se.impl.interceptors.PINoOpHandlerImpl;
+import com.sun.corba.se.impl.ior.IORTypeCheckRegistryImpl;
 import com.sun.corba.se.impl.ior.TaggedComponentFactoryFinderImpl;
 import com.sun.corba.se.impl.ior.TaggedProfileFactoryFinderImpl;
 import com.sun.corba.se.impl.ior.TaggedProfileTemplateFactoryFinderImpl;
@@ -226,6 +230,8 @@
 
     private ServiceContextRegistry serviceContextRegistry ;
 
+    private IORTypeCheckRegistry iorTypeCheckRegistry;
+
     // Needed here to implement connect/disconnect
     private TOAFactory toaFactory ;
 
@@ -274,6 +280,8 @@
     // insNamingDelegate.
     private final Object resolverLock = new Object() ;
 
+    private static final String IORTYPECHECKREGISTRY_FILTER_PROPNAME = "com.sun.CORBA.ORBIorTypeCheckRegistryFilter";
+
     private TaggedComponentFactoryFinder taggedComponentFactoryFinder ;
 
     private IdentifiableFactoryFinder taggedProfileFactoryFinder ;
@@ -411,6 +419,39 @@
             };
 
         serviceContextRegistry = new ServiceContextRegistry( this ) ;
+
+    }
+
+
+    private void initIORTypeCheckRegistry() {
+        String filterProps = AccessController
+                .doPrivileged(new PrivilegedAction<String>() {
+                    public String run() {
+                        String props = System
+                                .getProperty(IORTYPECHECKREGISTRY_FILTER_PROPNAME);
+                        if (props == null) {
+                            props = Security
+                                    .getProperty(IORTYPECHECKREGISTRY_FILTER_PROPNAME);
+                        }
+                        return props;
+                    }
+                });
+        if (filterProps != null) {
+            try {
+                iorTypeCheckRegistry = new IORTypeCheckRegistryImpl(filterProps, this);
+            } catch (Exception ex) {
+                throw wrapper.bootstrapException(ex);
+            }
+
+            if (this.orbInitDebugFlag) {
+                dprint(".initIORTypeCheckRegistry, IORTypeCheckRegistryImpl created for properties == "
+                        + filterProps);
+            }
+        } else {
+            if (this.orbInitDebugFlag) {
+                dprint(".initIORTypeCheckRegistry, IORTypeCheckRegistryImpl NOT created for properties == ");
+            }
+        }
     }
 
     protected void setDebugFlags( String[] args )
@@ -494,6 +535,8 @@
         getThreadPoolManager();
 
         super.getByteBufferPool();
+
+        initIORTypeCheckRegistry();
     }
 
     private synchronized POAFactory getPOAFactory()
@@ -2089,6 +2132,17 @@
         }
         return copierManager ;
     }
+
+    @Override
+    public void validateIORClass(String iorClassName) {
+        if (iorTypeCheckRegistry != null) {
+            if (!iorTypeCheckRegistry.isValidIORType(iorClassName)) {
+                throw ORBUtilSystemException.get( this,
+                        CORBALogDomains.OA_IOR ).badStringifiedIor();
+            }
+        }
+    }
+
 } // Class ORBImpl
 
 ////////////////////////////////////////////////////////////////////////
--- a/src/java.corba/share/classes/com/sun/corba/se/impl/orb/ORBSingleton.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.corba/share/classes/com/sun/corba/se/impl/orb/ORBSingleton.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, 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
@@ -768,6 +768,13 @@
     public CopierManager getCopierManager() {
         return null ;
     }
+
+    @Override
+    public void validateIORClass(String iorClassName) {
+        getFullORB().validateIORClass(iorClassName);
+
+    }
+
 }
 
 // End of file.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/java.corba/share/classes/com/sun/corba/se/spi/ior/IORTypeCheckRegistry.java	Fri Jan 19 09:32:10 2018 -0800
@@ -0,0 +1,31 @@
+/*
+ * Copyright (c) 2017, 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.corba.se.spi.ior;
+
+public interface IORTypeCheckRegistry {
+    public boolean isValidIORType(String iorClassName);
+}
+
--- a/src/java.corba/share/classes/com/sun/corba/se/spi/orb/ORB.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.corba/share/classes/com/sun/corba/se/spi/orb/ORB.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2017, 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
@@ -121,6 +121,7 @@
     public boolean shutdownDebugFlag = false;
     public boolean giopDebugFlag = false;
     public boolean invocationTimingDebugFlag = false ;
+    public boolean orbInitDebugFlag = false ;
 
     // SystemException log wrappers.  Protected so that they can be used in
     // subclasses.
@@ -487,6 +488,24 @@
     public abstract ThreadPoolManager getThreadPoolManager();
 
     public abstract CopierManager getCopierManager() ;
+
+    /*
+     * This method is called to verify that a stringified IOR passed to
+     * an org.omg.CORBA.ORB::string_to_object method contains a valid and acceptable IOR type.
+     * If an ORB is configured with IOR type checking enabled,
+     * the ORB executes a IOR type registry lookup to
+     * validate that the class name extract from a type id in
+     * a stringified IOR is a known and accepted type.
+     * A CORBA {@code org.omg.CORBA.DATA_CONVERSION} exception will be thrown should the type check fail.
+     *
+     * @param iorClassName
+     *        a string representing the class name corresponding to the type id of an IOR
+     * @throws org.omg.CORBA.DATA_CONVERSION
+     *           exception with an indication that it is a "Bad stringified IOR", which is thrown
+     *           when the type check fails.
+     */
+    public abstract void validateIORClass(String iorClassName);
+
 }
 
 // End of file.
--- a/src/java.desktop/share/classes/java/awt/color/ICC_ColorSpace.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.desktop/share/classes/java/awt/color/ICC_ColorSpace.java	Fri Jan 19 09:32:10 2018 -0800
@@ -128,6 +128,18 @@
     }
 
     /**
+     * Validate an ICC_ColorSpace read from an object input stream
+     */
+    private void readObject(java.io.ObjectInputStream s)
+        throws ClassNotFoundException, java.io.IOException {
+
+        s.defaultReadObject();
+        if (thisProfile == null) {
+            thisProfile = ICC_Profile.getInstance(ColorSpace.CS_sRGB);
+        }
+    }
+
+    /**
     * Returns the ICC_Profile for this ICC_ColorSpace.
     * @return the ICC_Profile for this ICC_ColorSpace.
     */
--- a/src/java.desktop/share/classes/java/awt/geom/Path2D.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.desktop/share/classes/java/awt/geom/Path2D.java	Fri Jan 19 09:32:10 2018 -0800
@@ -25,13 +25,14 @@
 
 package java.awt.geom;
 
+import java.awt.Rectangle;
 import java.awt.Shape;
-import java.awt.Rectangle;
-import sun.awt.geom.Curve;
 import java.io.Serializable;
 import java.io.StreamCorruptedException;
 import java.util.Arrays;
 
+import sun.awt.geom.Curve;
+
 /**
  * The {@code Path2D} class provides a simple, yet flexible
  * shape which represents an arbitrary geometric path.
@@ -2625,9 +2626,12 @@
             throw new java.io.InvalidObjectException(iae.getMessage());
         }
 
-        pointTypes = new byte[(nT < 0) ? INIT_SIZE : nT];
-        if (nC < 0) {
-            nC = INIT_SIZE * 2;
+        // Accept the size from the stream only if it is less than INIT_SIZE
+        // otherwise the size will be based on the real data in the stream
+        pointTypes = new byte[(nT < 0 || nT > INIT_SIZE) ? INIT_SIZE : nT];
+        final int initX2 = INIT_SIZE * 2;
+        if (nC < 0 || nC > initX2) {
+            nC = initX2;
         }
         if (storedbl) {
             ((Path2D.Double) this).doubleCoords = new double[nC];
--- a/src/java.desktop/share/classes/javax/swing/text/DefaultEditorKit.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.desktop/share/classes/javax/swing/text/DefaultEditorKit.java	Fri Jan 19 09:32:10 2018 -0800
@@ -110,7 +110,7 @@
      * @return the command list
      */
     public Action[] getActions() {
-        return defaultActions;
+        return defaultActions.clone();
     }
 
     /**
--- a/src/java.desktop/share/classes/javax/swing/text/html/CSS.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.desktop/share/classes/javax/swing/text/html/CSS.java	Fri Jan 19 09:32:10 2018 -0800
@@ -26,21 +26,27 @@
 
 import java.awt.Color;
 import java.awt.Font;
-import java.awt.GraphicsEnvironment;
-import java.awt.Toolkit;
 import java.awt.HeadlessException;
 import java.awt.Image;
-import java.io.*;
-import java.lang.reflect.Method;
+import java.awt.Toolkit;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.Serializable;
+import java.net.MalformedURLException;
 import java.net.URL;
-import java.net.MalformedURLException;
 import java.util.Enumeration;
 import java.util.Hashtable;
 import java.util.Vector;
-import java.util.Locale;
+
 import javax.swing.ImageIcon;
 import javax.swing.SizeRequirements;
-import javax.swing.text.*;
+import javax.swing.text.AttributeSet;
+import javax.swing.text.Element;
+import javax.swing.text.MutableAttributeSet;
+import javax.swing.text.SimpleAttributeSet;
+import javax.swing.text.StyleConstants;
+import javax.swing.text.StyleContext;
+import javax.swing.text.View;
 
 /**
  * Defines a set of
@@ -3568,7 +3574,7 @@
 
         // Reconstruct the hashtable.
         int numValues = s.readInt();
-        valueConvertor = new Hashtable<>(Math.max(1, numValues));
+        valueConvertor = new Hashtable<>();
         while (numValues-- > 0) {
             Object key = s.readObject();
             Object value = s.readObject();
--- a/src/java.desktop/share/native/liblcms/LCMS.c	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.desktop/share/native/liblcms/LCMS.c	Fri Jan 19 09:32:10 2018 -0800
@@ -644,7 +644,12 @@
 {
     jclass clsLcmsProfile;
     jobject cmmProfile;
-    jfieldID fid = (*env)->GetFieldID (env,
+    jfieldID fid;
+
+    if (pf == NULL) {
+        return NULL;
+    }
+    fid = (*env)->GetFieldID (env,
         (*env)->GetObjectClass(env, pf),
         "cmmProfile", "Lsun/java2d/cmm/Profile;");
     if (fid == NULL) {
--- a/src/java.desktop/share/native/libsplashscreen/libpng/pngpriv.h	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.desktop/share/native/libsplashscreen/libpng/pngpriv.h	Fri Jan 19 09:32:10 2018 -0800
@@ -284,11 +284,12 @@
 #  endif
 #endif /* PNG_MIPS_MSA_OPT > 0 */
 
+#ifdef PNG_POWERPC_VSX_API_SUPPORTED
 #if PNG_POWERPC_VSX_OPT > 0
 #  define PNG_FILTER_OPTIMIZATIONS png_init_filter_functions_vsx
 #  define PNG_POWERPC_VSX_IMPLEMENTATION 1
 #endif
-
+#endif
 
 /* Is this a build of a DLL where compilation of the object modules requires
  * different preprocessor settings to those required for a simple library?  If
--- a/src/java.desktop/unix/native/libawt_xawt/awt/gtk2_interface.c	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.desktop/unix/native/libawt_xawt/awt/gtk2_interface.c	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2017, 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
@@ -761,46 +761,41 @@
     }
 
     /*
-     * Strip the AT-SPI GTK_MODULEs if present
+     * Strip the AT-SPI GTK_MODULES if present
      */
     gtk_modules_env = getenv ("GTK_MODULES");
+    if ((gtk_modules_env && strstr(gtk_modules_env, "atk-bridge")) ||
+        (gtk_modules_env && strstr(gtk_modules_env, "gail"))) {
+        /* careful, strtok modifies its args */
+        gchar *tmp_env = strdup(gtk_modules_env);
+        if (tmp_env) {
+            /* the new env will be smaller than the old one */
+            gchar *s, *new_env = SAFE_SIZE_STRUCT_ALLOC(malloc,
+                    sizeof(ENV_PREFIX), 1, strlen (gtk_modules_env));
 
-    if (gtk_modules_env && strstr (gtk_modules_env, "atk-bridge") ||
-        gtk_modules_env && strstr (gtk_modules_env, "gail"))
-    {
-        /* the new env will be smaller than the old one */
-        gchar *s, *new_env = SAFE_SIZE_STRUCT_ALLOC(malloc,
-                sizeof(ENV_PREFIX), 1, strlen (gtk_modules_env));
-
-        if (new_env != NULL )
-        {
-            /* careful, strtok modifies its args */
-            gchar *tmp_env = strdup (gtk_modules_env);
-            strcpy(new_env, ENV_PREFIX);
+            if (new_env) {
+                strcpy(new_env, ENV_PREFIX);
 
-            /* strip out 'atk-bridge' and 'gail' */
-            size_t PREFIX_LENGTH = strlen(ENV_PREFIX);
-            while (s = strtok(tmp_env, ":"))
-            {
-                if ((!strstr (s, "atk-bridge")) && (!strstr (s, "gail")))
-                {
-                    if (strlen (new_env) > PREFIX_LENGTH) {
-                        new_env = strcat (new_env, ":");
+                /* strip out 'atk-bridge' and 'gail' */
+                size_t PREFIX_LENGTH = strlen(ENV_PREFIX);
+                gchar *tmp_ptr = NULL;
+                for (s = strtok_r(tmp_env, ":", &tmp_ptr); s;
+                     s = strtok_r(NULL, ":", &tmp_ptr)) {
+                    if ((!strstr(s, "atk-bridge")) && (!strstr(s, "gail"))) {
+                        if (strlen(new_env) > PREFIX_LENGTH) {
+                            new_env = strcat(new_env, ":");
+                        }
+                        new_env = strcat(new_env, s);
                     }
-                    new_env = strcat(new_env, s);
                 }
-                if (tmp_env)
-                {
-                    free (tmp_env);
-                    tmp_env = NULL; /* next call to strtok arg1==NULL */
+                if (putenv(new_env) != 0) {
+                    /* no free() on success, putenv() doesn't copy string */
+                    free(new_env);
                 }
             }
-            putenv (new_env);
-            free (new_env);
-            free (tmp_env);
+            free(tmp_env);
         }
     }
-
     /*
      * GTK should be initialized with gtk_init_check() before use.
      *
--- a/src/java.desktop/unix/native/libawt_xawt/awt/gtk3_interface.c	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.desktop/unix/native/libawt_xawt/awt/gtk3_interface.c	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2017, 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
@@ -580,42 +580,39 @@
     }
 
     /*
-     * Strip the AT-SPI GTK_MODULEs if present
+     * Strip the AT-SPI GTK_MODULES if present
      */
     gtk_modules_env = getenv ("GTK_MODULES");
-    if (gtk_modules_env && strstr (gtk_modules_env, "atk-bridge") ||
-        gtk_modules_env && strstr (gtk_modules_env, "gail"))
-    {
-        /* the new env will be smaller than the old one */
-        gchar *s, *new_env = SAFE_SIZE_STRUCT_ALLOC(malloc,
-                sizeof(ENV_PREFIX), 1, strlen (gtk_modules_env));
-
-        if (new_env != NULL )
-        {
-            /* careful, strtok modifies its args */
-            gchar *tmp_env = strdup (gtk_modules_env);
-            strcpy(new_env, ENV_PREFIX);
-
-            /* strip out 'atk-bridge' and 'gail' */
-            size_t PREFIX_LENGTH = strlen(ENV_PREFIX);
-            while (s = strtok(tmp_env, ":"))
-            {
-                if ((!strstr (s, "atk-bridge")) && (!strstr (s, "gail")))
-                {
-                    if (strlen (new_env) > PREFIX_LENGTH) {
-                        new_env = strcat (new_env, ":");
+    if ((gtk_modules_env && strstr(gtk_modules_env, "atk-bridge")) ||
+        (gtk_modules_env && strstr(gtk_modules_env, "gail"))) {
+        /* careful, strtok modifies its args */
+        gchar *tmp_env = strdup(gtk_modules_env);
+        if (tmp_env) {
+            /* the new env will be smaller than the old one */
+            gchar *s, *new_env = SAFE_SIZE_STRUCT_ALLOC(malloc,
+                    sizeof(ENV_PREFIX), 1, strlen (gtk_modules_env));
+
+            if (new_env) {
+                strcpy(new_env, ENV_PREFIX);
+
+                /* strip out 'atk-bridge' and 'gail' */
+                size_t PREFIX_LENGTH = strlen(ENV_PREFIX);
+                gchar *tmp_ptr = NULL;
+                for (s = strtok_r(tmp_env, ":", &tmp_ptr); s;
+                     s = strtok_r(NULL, ":", &tmp_ptr)) {
+                    if ((!strstr(s, "atk-bridge")) && (!strstr(s, "gail"))) {
+                        if (strlen(new_env) > PREFIX_LENGTH) {
+                            new_env = strcat(new_env, ":");
+                        }
+                        new_env = strcat(new_env, s);
                     }
-                    new_env = strcat(new_env, s);
                 }
-                if (tmp_env)
-                {
-                    free (tmp_env);
-                    tmp_env = NULL; /* next call to strtok arg1==NULL */
+                if (putenv(new_env) != 0) {
+                    /* no free() on success, putenv() doesn't copy string */
+                    free(new_env);
                 }
             }
-            putenv (new_env);
-            free (new_env);
-            free (tmp_env);
+            free(tmp_env);
         }
     }
     /*
--- a/src/java.desktop/windows/native/libawt/java2d/d3d/D3DGraphicsDevice.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.desktop/windows/native/libawt/java2d/d3d/D3DGraphicsDevice.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -98,7 +98,7 @@
 
     jstring ret = JNU_NewStringPlatform(env, pAdapterId);
 
-    delete pAdapterId;
+    delete[] pAdapterId;
 
     return ret;
 }
--- a/src/java.desktop/windows/native/libawt/windows/WPrinterJob.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.desktop/windows/native/libawt/windows/WPrinterJob.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -508,14 +508,14 @@
           names = env->NewObjectArray(cReturned, cls, NULL);
       }
       if (names == NULL || cls == NULL) {
-          delete buf;
+          delete[] buf;
           return names;
       }
 
       for (int i = 0; i < cReturned; i++) {
           utf_str = JNU_NewStringPlatform(env, buf+(buf_len*i));
             if (utf_str == NULL) {
-                delete buf;
+                delete[] buf;
                 return names;
             }
             env->SetObjectArrayElement(names, i, utf_str);
--- a/src/java.desktop/windows/native/libawt/windows/awt_Palette.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.desktop/windows/native/libawt/windows/awt_Palette.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2017, 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
@@ -148,7 +148,7 @@
         pEntry->peFlags = PC_EXPLICIT;
     }
     hPal = ::CreatePalette(pLogPal);
-    delete pLogPal;
+    delete[] pLogPal;
     if ( hPal == 0 ) {
         return 0;
     }
--- a/src/java.desktop/windows/native/libawt/windows/awt_Robot.cpp	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.desktop/windows/native/libawt/windows/awt_Robot.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -285,7 +285,7 @@
 
     // copy pixels into Java array
     env->SetIntArrayRegion(pixelArray, 0, numPixels, (jint *)pixelData);
-    delete pinfo;
+    delete[] pinfo;
 
     // free all the GDI objects we made
     ::SelectObject(hdcMem, hOldBitmap);
--- a/src/java.naming/share/classes/javax/naming/directory/BasicAttributes.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.naming/share/classes/javax/naming/directory/BasicAttributes.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2017, 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
@@ -302,8 +302,8 @@
         s.defaultReadObject();  // read in the ignoreCase flag
         int n = s.readInt();    // number of attributes
         attrs = (n >= 1)
-            ? new Hashtable<String,Attribute>(n * 2)
-            : new Hashtable<String,Attribute>(2); // can't have initial size of 0 (grrr...)
+                ? new Hashtable<>(1 + (int) (Math.min(768, n) / .75f))
+                : new Hashtable<>(2); // can't have initial size of 0 (grrr...)
         while (--n >= 0) {
             put((Attribute)s.readObject());
         }
--- a/src/java.naming/share/classes/sun/security/provider/certpath/ldap/LDAPCertStore.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.naming/share/classes/sun/security/provider/certpath/ldap/LDAPCertStore.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2017, 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
@@ -136,6 +136,11 @@
                         + params.getClass().getName() + " passed");
         }
 
+        SecurityManager security = System.getSecurityManager();
+        if (security != null) {
+            security.checkConnect(serverName, port);
+        }
+
         Key k = new Key(serverName, port);
         LDAPCertStoreImpl lci = certStoreCache.get(k);
         if (lci == null) {
--- a/src/java.naming/share/classes/sun/security/provider/certpath/ldap/LDAPCertStoreImpl.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.naming/share/classes/sun/security/provider/certpath/ldap/LDAPCertStoreImpl.java	Fri Jan 19 09:32:10 2018 -0800
@@ -26,9 +26,11 @@
 package sun.security.provider.certpath.ldap;
 
 import java.io.ByteArrayInputStream;
-import java.io.IOException;
+import java.net.URI;
 import java.util.*;
+import javax.naming.CompositeName;
 import javax.naming.Context;
+import javax.naming.InvalidNameException;
 import javax.naming.NamingEnumeration;
 import javax.naming.NamingException;
 import javax.naming.NameNotFoundException;
@@ -44,6 +46,7 @@
 import javax.naming.ldap.LdapContext;
 import javax.security.auth.x500.X500Principal;
 
+import com.sun.jndi.ldap.LdapReferralException;
 import sun.security.util.HexDumpEncoder;
 import sun.security.provider.certpath.X509CertificatePair;
 import sun.security.util.Cache;
@@ -181,13 +184,9 @@
         try {
             ctx = new InitialLdapContext(env, null);
             /*
-             * By default, follow referrals unless application has
-             * overridden property in an application resource file.
+             * Always deal with referrals here.
              */
-            Hashtable<?,?> currentEnv = ctx.getEnvironment();
-            if (currentEnv.get(Context.REFERRAL) == null) {
-                ctx.addToEnvironment(Context.REFERRAL, "follow-scheme");
-            }
+            ctx.addToEnvironment(Context.REFERRAL, "throw");
         } catch (NamingException e) {
             if (debug != null) {
                 debug.println("LDAPCertStore.engineInit about to throw "
@@ -223,11 +222,25 @@
         private Map<String, byte[][]> valueMap;
         private final List<String> requestedAttributes;
 
-        LDAPRequest(String name) {
-            this.name = name;
+        LDAPRequest(String name) throws CertStoreException {
+            this.name = checkName(name);
             requestedAttributes = new ArrayList<>(5);
         }
 
+        private String checkName(String name) throws CertStoreException {
+            if (name == null) {
+                throw new CertStoreException("Name absent");
+            }
+            try {
+                if (new CompositeName(name).size() > 1) {
+                    throw new CertStoreException("Invalid name: " + name);
+                }
+            } catch (InvalidNameException ine) {
+                throw new CertStoreException("Invalid name: " + name, ine);
+            }
+            return name;
+        }
+
         String getName() {
             return name;
         }
@@ -242,7 +255,6 @@
         /**
          * Gets one or more binary values from an attribute.
          *
-         * @param name          the location holding the attribute
          * @param attrId                the attribute identifier
          * @return                      an array of binary values (byte arrays)
          * @throws NamingException      if a naming exception occurs
@@ -300,6 +312,39 @@
 
             try {
                 attrs = ctx.getAttributes(name, attrIds);
+            } catch (LdapReferralException lre) {
+                // LdapCtx has a hopCount field to avoid infinite loop
+                while (true) {
+                    try {
+                        String newName = (String) lre.getReferralInfo();
+                        URI newUri = new URI(newName);
+                        if (!newUri.getScheme().equalsIgnoreCase("ldap")) {
+                            throw new IllegalArgumentException("Not LDAP");
+                        }
+                        String newDn = newUri.getPath();
+                        if (newDn != null && newDn.charAt(0) == '/') {
+                            newDn = newDn.substring(1);
+                        }
+                        checkName(newDn);
+                    } catch (Exception e) {
+                        throw new NamingException("Cannot follow referral to "
+                                + lre.getReferralInfo());
+                    }
+                    LdapContext refCtx =
+                            (LdapContext)lre.getReferralContext();
+
+                    // repeat the original operation at the new context
+                    try {
+                        attrs = refCtx.getAttributes(name, attrIds);
+                        break;
+                    } catch (LdapReferralException re) {
+                        lre = re;
+                        continue;
+                    } finally {
+                        // Make sure we close referral context
+                        refCtx.close();
+                    }
+                }
             } catch (CommunicationException ce) {
                 communicationError = true;
                 throw ce;
@@ -513,7 +558,7 @@
      * <code>X509CertSelector</code>), a <code>CertStoreException</code> is
      * thrown.
      *
-     * @param selector a <code>X509CertSelector</code> used to select which
+     * @param xsel a <code>X509CertSelector</code> used to select which
      *  <code>Certificate</code>s should be returned.
      * @return a <code>Collection</code> of <code>X509Certificate</code>s that
      *         match the specified selector
@@ -684,7 +729,7 @@
      * (or the selector is not an <code>X509CRLSelector</code>), a
      * <code>CertStoreException</code> is thrown.
      *
-     * @param selector A <code>X509CRLSelector</code> used to select which
+     * @param xsel A <code>X509CRLSelector</code> used to select which
      *  <code>CRL</code>s should be returned. Specify <code>null</code>
      *  to return all <code>CRL</code>s.
      * @return A <code>Collection</code> of <code>X509CRL</code>s that
--- a/src/java.rmi/share/classes/sun/rmi/registry/RegistryImpl.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.rmi/share/classes/sun/rmi/registry/RegistryImpl.java	Fri Jan 19 09:32:10 2018 -0800
@@ -177,7 +177,7 @@
             }
         } else {
             LiveRef lref = new LiveRef(id, port, csf, ssf);
-            setup(new UnicastServerRef2(lref, RegistryImpl::registryFilter));
+            setup(new UnicastServerRef2(lref, serialFilter));
         }
     }
 
--- a/src/java.security.jgss/share/classes/sun/net/www/protocol/http/spnego/NegotiateCallbackHandler.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.security.jgss/share/classes/sun/net/www/protocol/http/spnego/NegotiateCallbackHandler.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2017, 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,6 +35,7 @@
 import javax.security.auth.callback.PasswordCallback;
 import javax.security.auth.callback.UnsupportedCallbackException;
 import sun.net.www.protocol.http.HttpCallerInfo;
+import sun.security.jgss.LoginConfigImpl;
 
 /**
  * @since 1.6
@@ -61,19 +62,28 @@
     private void getAnswer() {
         if (!answered) {
             answered = true;
-            PasswordAuthentication passAuth =
-                    Authenticator.requestPasswordAuthentication(
-                    hci.authenticator,
-                    hci.host, hci.addr, hci.port, hci.protocol,
-                    hci.prompt, hci.scheme, hci.url, hci.authType);
-            /**
-             * To be compatible with existing callback handler implementations,
-             * when the underlying Authenticator is canceled, username and
-             * password are assigned null. No exception is thrown.
-             */
-            if (passAuth != null) {
-                username = passAuth.getUserName();
-                password = passAuth.getPassword();
+            Authenticator auth;
+            if (hci.authenticator != null) {
+                auth = hci.authenticator;
+            } else {
+                auth = LoginConfigImpl.HTTP_USE_GLOBAL_CREDS ?
+                        Authenticator.getDefault() : null;
+            }
+
+            if (auth != null) {
+                PasswordAuthentication passAuth =
+                        auth.requestPasswordAuthenticationInstance(
+                                hci.host, hci.addr, hci.port, hci.protocol,
+                                hci.prompt, hci.scheme, hci.url, hci.authType);
+                /**
+                 * To be compatible with existing callback handler implementations,
+                 * when the underlying Authenticator is canceled, username and
+                 * password are assigned null. No exception is thrown.
+                 */
+                if (passAuth != null) {
+                    username = passAuth.getUserName();
+                    password = passAuth.getPassword();
+                }
             }
         }
     }
--- a/src/java.security.jgss/share/classes/sun/security/jgss/GSSUtil.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.security.jgss/share/classes/sun/security/jgss/GSSUtil.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2017, 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
@@ -270,24 +270,17 @@
      */
     public static boolean useSubjectCredsOnly(GSSCaller caller) {
 
-        // HTTP/SPNEGO doesn't use the standard JAAS framework. Instead, it
-        // uses the java.net.Authenticator style, therefore always return
-        // false here.
+        String propValue = GetPropertyAction.privilegedGetProperty(
+                "javax.security.auth.useSubjectCredsOnly");
+
+        // Invalid values should be ignored and the default assumed.
         if (caller instanceof HttpCaller) {
-            return false;
+            // Default for HTTP/SPNEGO is false.
+            return "true".equalsIgnoreCase(propValue);
+        } else {
+            // Default for JGSS is true.
+            return !("false".equalsIgnoreCase(propValue));
         }
-        /*
-         * Don't use GetBooleanAction because the default value in the JRE
-         * (when this is unset) has to treated as true.
-         */
-        String propValue = AccessController.doPrivileged(
-                new GetPropertyAction("javax.security.auth.useSubjectCredsOnly",
-                "true"));
-        /*
-         * This property has to be explicitly set to "false". Invalid
-         * values should be ignored and the default "true" assumed.
-         */
-        return (!propValue.equalsIgnoreCase("false"));
     }
 
     /**
--- a/src/java.security.jgss/share/classes/sun/security/jgss/LoginConfigImpl.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.security.jgss/share/classes/sun/security/jgss/LoginConfigImpl.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2017, 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
@@ -29,6 +29,7 @@
 import javax.security.auth.login.AppConfigurationEntry;
 import javax.security.auth.login.Configuration;
 import org.ietf.jgss.Oid;
+import sun.security.action.GetPropertyAction;
 
 /**
  * A Configuration implementation especially designed for JGSS.
@@ -44,6 +45,16 @@
     private static final sun.security.util.Debug debug =
         sun.security.util.Debug.getInstance("gssloginconfig", "\t[GSS LoginConfigImpl]");
 
+    public static final boolean HTTP_USE_GLOBAL_CREDS;
+
+    static {
+        String prop = GetPropertyAction
+                .privilegedGetProperty("http.use.global.creds");
+        //HTTP_USE_GLOBAL_CREDS = "true".equalsIgnoreCase(prop); // default false
+        HTTP_USE_GLOBAL_CREDS = !"false".equalsIgnoreCase(prop); // default true
+    }
+
+
     /**
      * A new instance of LoginConfigImpl must be created for each login request
      * since it's only used by a single (caller, mech) pair
@@ -178,7 +189,11 @@
                 options.put("principal", "*");
                 options.put("isInitiator", "false");
             } else {
-                options.put("useTicketCache", "true");
+                if (caller instanceof HttpCaller && !HTTP_USE_GLOBAL_CREDS) {
+                    options.put("useTicketCache", "false");
+                } else {
+                    options.put("useTicketCache", "true");
+                }
                 options.put("doNotPrompt", "false");
             }
             return new AppConfigurationEntry[] {
--- a/src/java.security.jgss/share/native/libj2gss/GSSLibStub.c	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.security.jgss/share/native/libj2gss/GSSLibStub.c	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2017, 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
@@ -830,7 +830,7 @@
 {
   OM_uint32 minor, major;
   gss_cred_id_t credHdl ;
-  gss_ctx_id_t contextHdl;
+  gss_ctx_id_t contextHdl, contextHdlSave;
   gss_name_t targetName;
   gss_OID mech;
   OM_uint32 flags, aFlags;
@@ -847,7 +847,7 @@
   TRACE0("[GSSLibStub_initContext]");
 
   credHdl = (gss_cred_id_t) jlong_to_ptr(pCred);
-  contextHdl = (gss_ctx_id_t) jlong_to_ptr(
+  contextHdl = contextHdlSave = (gss_ctx_id_t) jlong_to_ptr(
     (*env)->GetLongField(env, jcontextSpi, FID_NativeGSSContext_pContext));
   targetName = (gss_name_t) jlong_to_ptr(pName);
   mech = (gss_OID) jlong_to_ptr((*env)->GetLongField(env, jobj, FID_GSSLibStub_pMech));
@@ -882,10 +882,17 @@
   TRACE2("[GSSLibStub_initContext] after: pContext=%ld, outToken len=%ld",
             (long)contextHdl, (long)outToken.length);
 
+  // update context handle with the latest value if changed
+  // this is to work with both MIT and Solaris. Former deletes half-built
+  // context if error occurs
+  if (contextHdl != contextHdlSave) {
+    (*env)->SetLongField(env, jcontextSpi, FID_NativeGSSContext_pContext,
+                         ptr_to_jlong(contextHdl));
+    TRACE1("[GSSLibStub_initContext] set pContext=%ld", (long)contextHdl);
+  }
+
   if (GSS_ERROR(major) == GSS_S_COMPLETE) {
     /* update member values if needed */
-    (*env)->SetLongField(env, jcontextSpi, FID_NativeGSSContext_pContext,
-                        ptr_to_jlong(contextHdl));
     (*env)->SetIntField(env, jcontextSpi, FID_NativeGSSContext_flags, aFlags);
     TRACE1("[GSSLibStub_initContext] set flags=0x%x", aFlags);
 
@@ -939,7 +946,7 @@
 {
   OM_uint32 minor, major;
   OM_uint32 minor2, major2;
-  gss_ctx_id_t contextHdl;
+  gss_ctx_id_t contextHdl, contextHdlSave;
   gss_cred_id_t credHdl;
   gss_buffer_desc inToken;
   gss_channel_bindings_t cb;
@@ -959,7 +966,7 @@
 
   TRACE0("[GSSLibStub_acceptContext]");
 
-  contextHdl = (gss_ctx_id_t)jlong_to_ptr(
+  contextHdl = contextHdlSave = (gss_ctx_id_t)jlong_to_ptr(
     (*env)->GetLongField(env, jcontextSpi, FID_NativeGSSContext_pContext));
   credHdl = (gss_cred_id_t) jlong_to_ptr(pCred);
   initGSSBuffer(env, jinToken, &inToken);
@@ -996,19 +1003,22 @@
   TRACE3("[GSSLibStub_acceptContext] after: pCred=%ld, pContext=%ld, pDelegCred=%ld",
         (long)credHdl, (long)contextHdl, (long) delCred);
 
+  // update context handle with the latest value if changed
+  // this is to work with both MIT and Solaris. Former deletes half-built
+  // context if error occurs
+  if (contextHdl != contextHdlSave) {
+    (*env)->SetLongField(env, jcontextSpi, FID_NativeGSSContext_pContext,
+                         ptr_to_jlong(contextHdl));
+    TRACE1("[GSSLibStub_acceptContext] set pContext=%ld", (long)contextHdl);
+  }
+
   if (GSS_ERROR(major) == GSS_S_COMPLETE) {
     /* update member values if needed */
-    (*env)->SetLongField(env, jcontextSpi, FID_NativeGSSContext_pContext,
-                        ptr_to_jlong(contextHdl));
-    TRACE1("[GSSLibStub_acceptContext] set pContext=%ld",
-            (long)contextHdl);
-
     // WORKAROUND for a Heimdal bug
     if (delCred == GSS_C_NO_CREDENTIAL) {
         aFlags &= 0xfffffffe;
     }
     (*env)->SetIntField(env, jcontextSpi, FID_NativeGSSContext_flags, aFlags);
-
     TRACE1("[GSSLibStub_acceptContext] set flags=0x%x", aFlags);
 
     if (setTarget) {
--- a/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/lib/ExsltDynamic.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/lib/ExsltDynamic.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,6 +1,5 @@
 /*
- * reserved comment block
- * DO NOT REMOVE OR ALTER!
+ * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * Licensed to the Apache Software Foundation (ASF) under one or more
@@ -36,6 +35,7 @@
 import com.sun.org.apache.xpath.internal.objects.XNodeSet;
 import com.sun.org.apache.xpath.internal.objects.XNumber;
 import com.sun.org.apache.xpath.internal.objects.XObject;
+import jdk.xml.internal.JdkXmlUtils;
 
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
@@ -410,10 +410,7 @@
         {
           if (lDoc == null)
           {
-            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
-            dbf.setNamespaceAware(true);
-            DocumentBuilder db = dbf.newDocumentBuilder();
-            lDoc = db.newDocument();
+            lDoc = JdkXmlUtils.getDOMDocument();
           }
 
           Element element = null;
--- a/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/lib/ExsltStrings.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/lib/ExsltStrings.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,6 +1,5 @@
 /*
- * reserved comment block
- * DO NOT REMOVE OR ALTER!
+ * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * Licensed to the Apache Software Foundation (ASF) under one or more
@@ -22,12 +21,8 @@
 package com.sun.org.apache.xalan.internal.lib;
 
 import java.util.StringTokenizer;
-
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.parsers.FactoryConfigurationError;
-import javax.xml.parsers.ParserConfigurationException;
-
 import com.sun.org.apache.xpath.internal.NodeSet;
+import jdk.xml.internal.JdkXmlUtils;
 
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
@@ -51,7 +46,6 @@
  */
 public class ExsltStrings extends ExsltBase
 {
-   static final String JDK_DEFAULT_DOM = "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl";
 
   /**
    * The str:align function aligns a string within another string.
@@ -226,7 +220,7 @@
         token = str.substring(fromIndex);
       }
 
-      Document doc = getDocument();
+      Document doc = JdkXmlUtils.getDOMDocument();
       synchronized (doc)
       {
         Element element = doc.createElement("token");
@@ -290,7 +284,7 @@
     {
       StringTokenizer lTokenizer = new StringTokenizer(toTokenize, delims);
 
-      Document doc = getDocument();
+      Document doc = JdkXmlUtils.getDOMDocument();
       synchronized (doc)
       {
         while (lTokenizer.hasMoreTokens())
@@ -306,7 +300,7 @@
     else
     {
 
-      Document doc = getDocument();
+      Document doc = JdkXmlUtils.getDOMDocument();
       synchronized (doc)
       {
         for (int i = 0; i < toTokenize.length(); i++)
@@ -328,23 +322,4 @@
   {
     return tokenize(toTokenize, " \t\n\r");
   }
-
-    /**
-   * @return an instance of DOM Document
-     */
-   private static Document getDocument()
-   {
-        try
-        {
-            if (System.getSecurityManager() == null) {
-                return DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
-            } else {
-                return DocumentBuilderFactory.newInstance(JDK_DEFAULT_DOM, null).newDocumentBuilder().newDocument();
-            }
-        }
-        catch(ParserConfigurationException pce)
-        {
-            throw new com.sun.org.apache.xml.internal.utils.WrappedRuntimeException(pce);
-        }
-    }
 }
--- a/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/lib/Extensions.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/lib/Extensions.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,6 +1,5 @@
 /*
- * reserved comment block
- * DO NOT REMOVE OR ALTER!
+ * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * Licensed to the Apache Software Foundation (ASF) under one or more
@@ -23,14 +22,12 @@
 
 import java.util.StringTokenizer;
 
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.parsers.ParserConfigurationException;
-
 import com.sun.org.apache.xalan.internal.extensions.ExpressionContext;
 import com.sun.org.apache.xpath.internal.NodeSet;
 import com.sun.org.apache.xpath.internal.objects.XBoolean;
 import com.sun.org.apache.xpath.internal.objects.XNumber;
 import com.sun.org.apache.xpath.internal.objects.XObject;
+import jdk.xml.internal.JdkXmlUtils;
 
 import org.w3c.dom.Document;
 import org.w3c.dom.DocumentFragment;
@@ -51,7 +48,6 @@
  */
 public class Extensions
 {
-    static final String JDK_DEFAULT_DOM = "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl";
   /**
    * Constructor Extensions
    *
@@ -110,7 +106,7 @@
 
       // This no longer will work right since the DTM.
       // Document myDoc = myProcessor.getContextNode().getOwnerDocument();
-      Document myDoc = getDocument();
+      Document myDoc = JdkXmlUtils.getDOMDocument();
 
         Text textNode = myDoc.createTextNode(textNodeValue);
         DocumentFragment docFrag = myDoc.createDocumentFragment();
@@ -236,7 +232,7 @@
   public static NodeList tokenize(String toTokenize, String delims)
   {
 
-    Document doc = getDocument();
+    Document doc = JdkXmlUtils.getDOMDocument();
 
     StringTokenizer lTokenizer = new StringTokenizer(toTokenize, delims);
     NodeSet resultSet = new NodeSet();
@@ -269,23 +265,4 @@
   {
     return tokenize(toTokenize, " \t\n\r");
   }
-
-    /**
-   * @return an instance of DOM Document
-     */
-   private static Document getDocument()
-   {
-        try
-        {
-            if (System.getSecurityManager() == null) {
-                return DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
-            } else {
-                return DocumentBuilderFactory.newInstance(JDK_DEFAULT_DOM, null).newDocumentBuilder().newDocument();
-            }
-        }
-        catch(ParserConfigurationException pce)
-        {
-            throw new com.sun.org.apache.xml.internal.utils.WrappedRuntimeException(pce);
-        }
-    }
 }
--- a/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/utils/FactoryImpl.java	Thu Jan 18 11:22:28 2018 +0530
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,57 +0,0 @@
-/*
- * Copyright (c) 2011, 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.xalan.internal.utils;
-
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.parsers.SAXParserFactory;
-
-/**
- *
- * @author huizhe wang
- */
-public class FactoryImpl {
-
-    static final String DBF = "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl";
-    static final String SF = "com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl";
-
-    static public DocumentBuilderFactory getDOMFactory(boolean useServicesMechanism) {
-        DocumentBuilderFactory dbf =
-            useServicesMechanism ?
-            DocumentBuilderFactory.newInstance() :
-            DocumentBuilderFactory.newInstance( DBF,
-                FactoryImpl.class.getClassLoader());
-
-        return dbf;
-    }
-    static public SAXParserFactory getSAXFactory(boolean useServicesMechanism) {
-                SAXParserFactory factory =
-                    useServicesMechanism ?
-                    SAXParserFactory.newInstance() :
-                    SAXParserFactory.newInstance(SF,
-                        FactoryImpl.class.getClassLoader());
-                return factory;
-    }
-}
--- a/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/Translet.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/Translet.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,6 @@
 /*
- * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2017, Oracle and/or its affiliates. All rights reserved.
+ * @LastModified: Oct 2017
  */
 /*
  * Licensed to the Apache Software Foundation (ASF) under one or more
@@ -49,7 +50,7 @@
     public String[] getUrisArray();
     public int[]    getTypesArray();
     public String[] getNamespaceArray();
-    public boolean useServicesMechnism();
-    public void setServicesMechnism(boolean flag);
+    public boolean overrideDefaultParser();
+    public void setOverrideDefaultParser(boolean flag);
 
 }
--- a/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/compiler/Parser.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/compiler/Parser.java	Fri Jan 19 09:32:10 2018 -0800
@@ -22,7 +22,6 @@
 
 import com.sun.java_cup.internal.runtime.Symbol;
 import com.sun.org.apache.xalan.internal.XalanConstants;
-import com.sun.org.apache.xalan.internal.utils.FactoryImpl;
 import com.sun.org.apache.xalan.internal.utils.ObjectFactory;
 import com.sun.org.apache.xalan.internal.utils.XMLSecurityManager;
 import com.sun.org.apache.xalan.internal.xsltc.compiler.util.ErrorMsg;
@@ -43,9 +42,6 @@
 import java.util.StringTokenizer;
 import javax.xml.XMLConstants;
 import javax.xml.catalog.CatalogFeatures;
-import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.parsers.SAXParser;
-import javax.xml.parsers.SAXParserFactory;
 import jdk.xml.internal.JdkXmlFeatures;
 import jdk.xml.internal.JdkXmlUtils;
 import jdk.xml.internal.SecuritySupport;
@@ -56,7 +52,6 @@
 import org.xml.sax.SAXException;
 import org.xml.sax.SAXNotRecognizedException;
 import org.xml.sax.SAXNotSupportedException;
-import org.xml.sax.SAXParseException;
 import org.xml.sax.XMLReader;
 import org.xml.sax.helpers.AttributesImpl;
 
@@ -101,11 +96,11 @@
 
     private int _currentImportPrecedence;
 
-    private boolean _useServicesMechanism = true;
+    private boolean _overrideDefaultParser;
 
-    public Parser(XSLTC xsltc, boolean useServicesMechanism) {
+    public Parser(XSLTC xsltc, boolean useOverrideDefaultParser) {
         _xsltc = xsltc;
-        _useServicesMechanism = useServicesMechanism;
+        _overrideDefaultParser = useOverrideDefaultParser;
     }
 
     public void init() {
@@ -465,56 +460,35 @@
      */
     public SyntaxTreeNode parse(InputSource input) {
         try {
-            // Create a SAX parser and get the XMLReader object it uses
-            final SAXParserFactory factory = FactoryImpl.getSAXFactory(_useServicesMechanism);
-
-            if (_xsltc.isSecureProcessing()) {
-                try {
-                    factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
-                }
-                catch (SAXException e) {}
-            }
+            final XMLReader reader = JdkXmlUtils.getXMLReader(_overrideDefaultParser,
+                    _xsltc.isSecureProcessing());
 
-            try {
-                factory.setFeature(Constants.NAMESPACE_FEATURE,true);
-            }
-            catch (ParserConfigurationException | SAXNotRecognizedException | SAXNotSupportedException e) {
-                factory.setNamespaceAware(true);
-            }
+            JdkXmlUtils.setXMLReaderPropertyIfSupport(reader, XMLConstants.ACCESS_EXTERNAL_DTD,
+                    _xsltc.getProperty(XMLConstants.ACCESS_EXTERNAL_DTD), true);
 
-            final SAXParser parser = factory.newSAXParser();
-            try {
-                parser.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD,
-                        _xsltc.getProperty(XMLConstants.ACCESS_EXTERNAL_DTD));
-            } catch (SAXNotRecognizedException e) {
-                ErrorMsg err = new ErrorMsg(ErrorMsg.WARNING_MSG,
-                        parser.getClass().getName() + ": " + e.getMessage());
-                reportError(WARNING, err);
-            }
 
             boolean supportCatalog = true;
             boolean useCatalog = _xsltc.getFeature(JdkXmlFeatures.XmlFeature.USE_CATALOG);
             try {
-                factory.setFeature(JdkXmlUtils.USE_CATALOG,useCatalog);
+                reader.setFeature(JdkXmlUtils.USE_CATALOG, useCatalog);
             }
-            catch (ParserConfigurationException | SAXNotRecognizedException | SAXNotSupportedException e) {
+            catch (SAXNotRecognizedException | SAXNotSupportedException e) {
                 supportCatalog = false;
             }
 
             if (supportCatalog && useCatalog) {
                 try {
                     CatalogFeatures cf = (CatalogFeatures)_xsltc.getProperty(JdkXmlFeatures.CATALOG_FEATURES);
-                    if (cf != null) {
-                        for (CatalogFeatures.Feature f : CatalogFeatures.Feature.values()) {
-                            parser.setProperty(f.getPropertyName(), cf.get(f));
+                        if (cf != null) {
+                            for (CatalogFeatures.Feature f : CatalogFeatures.Feature.values()) {
+                                reader.setProperty(f.getPropertyName(), cf.get(f));
+                            }
                         }
-                    }
                 } catch (SAXNotRecognizedException e) {
                     //shall not happen for internal settings
                 }
             }
 
-            final XMLReader reader = parser.getXMLReader();
             String lastProperty = "";
             try {
                 XMLSecurityManager securityManager =
@@ -525,7 +499,7 @@
                 }
                 if (securityManager.printEntityCountInfo()) {
                     lastProperty = XalanConstants.JDK_ENTITY_COUNT_INFO;
-                    parser.setProperty(XalanConstants.JDK_ENTITY_COUNT_INFO, XalanConstants.JDK_YES);
+                    reader.setProperty(XalanConstants.JDK_ENTITY_COUNT_INFO, XalanConstants.JDK_YES);
                 }
             } catch (SAXException se) {
                 XMLSecurityManager.printWarning(reader.getClass().getName(), lastProperty, se);
@@ -537,13 +511,6 @@
 
             return(parse(reader, input));
         }
-        catch (ParserConfigurationException e) {
-            ErrorMsg err = new ErrorMsg(ErrorMsg.SAX_PARSER_CONFIG_ERR);
-            reportError(ERROR, err);
-        }
-        catch (SAXParseException e){
-            reportError(ERROR, new ErrorMsg(e.getMessage(),e.getLineNumber()));
-        }
         catch (SAXException e) {
             reportError(ERROR, new ErrorMsg(e.getMessage()));
         }
--- a/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/compiler/XSLTC.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/compiler/XSLTC.java	Fri Jan 19 09:32:10 2018 -0800
@@ -135,7 +135,7 @@
      */
     private boolean _isSecureProcessing = false;
 
-    private boolean _useServicesMechanism = true;
+    private boolean _overrideDefaultParser;
 
     /**
      * protocols allowed for external references set by the stylesheet processing instruction, Import and Include element.
@@ -175,8 +175,10 @@
     /**
      * XSLTC compiler constructor
      */
-    public XSLTC(boolean useServicesMechanism, JdkXmlFeatures featureManager) {
-        _parser = new Parser(this, useServicesMechanism);
+    public XSLTC(JdkXmlFeatures featureManager) {
+        _overrideDefaultParser = featureManager.getFeature(
+                JdkXmlFeatures.XmlFeature.JDK_OVERRIDE_PARSER);
+        _parser = new Parser(this, _overrideDefaultParser);
         _xmlFeatures = featureManager;
         _extensionClassLoader = null;
         _externalExtensionFunctions = new HashMap<>();
@@ -195,19 +197,6 @@
     public boolean isSecureProcessing() {
         return _isSecureProcessing;
     }
-    /**
-     * Return the state of the services mechanism feature.
-     */
-    public boolean useServicesMechnism() {
-        return _useServicesMechanism;
-    }
-
-    /**
-     * Set the state of the services mechanism feature.
-     */
-    public void setServicesMechnism(boolean flag) {
-        _useServicesMechanism = flag;
-    }
 
      /**
      * Return the value of the specified feature
--- a/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/runtime/AbstractTranslet.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/runtime/AbstractTranslet.java	Fri Jan 19 09:32:10 2018 -0800
@@ -21,7 +21,6 @@
 package com.sun.org.apache.xalan.internal.xsltc.runtime;
 
 import com.sun.org.apache.xalan.internal.XalanConstants;
-import com.sun.org.apache.xalan.internal.utils.FactoryImpl;
 import com.sun.org.apache.xalan.internal.xsltc.DOM;
 import com.sun.org.apache.xalan.internal.xsltc.DOMCache;
 import com.sun.org.apache.xalan.internal.xsltc.DOMEnhancedForDTM;
@@ -45,6 +44,7 @@
 import javax.xml.parsers.DocumentBuilderFactory;
 import javax.xml.parsers.ParserConfigurationException;
 import javax.xml.transform.Templates;
+import jdk.xml.internal.JdkXmlUtils;
 import org.w3c.dom.DOMImplementation;
 import org.w3c.dom.Document;
 
@@ -106,7 +106,7 @@
     // This is the name of the index used for ID attributes
     private final static String ID_INDEX_NAME = "##id";
 
-    private boolean _useServicesMechanism;
+    private boolean _overrideDefaultParser;
 
     // The OutputStream for redirect function
     private FileOutputStream output = null;
@@ -559,7 +559,7 @@
     {
         try {
             final TransletOutputHandlerFactory factory
-                = TransletOutputHandlerFactory.newInstance();
+                = TransletOutputHandlerFactory.newInstance(_overrideDefaultParser);
 
             String dirStr = new File(filename).getParent();
             if ((null != dirStr) && (dirStr.length() > 0)) {
@@ -761,15 +761,15 @@
     /**
      * Return the state of the services mechanism feature.
      */
-    public boolean useServicesMechnism() {
-        return _useServicesMechanism;
+    public boolean overrideDefaultParser() {
+        return _overrideDefaultParser;
     }
 
     /**
      * Set the state of the services mechanism feature.
      */
-    public void setServicesMechnism(boolean flag) {
-        _useServicesMechanism = flag;
+    public void setOverrideDefaultParser(boolean flag) {
+        _overrideDefaultParser = flag;
     }
 
     /**
@@ -795,7 +795,7 @@
         throws ParserConfigurationException
     {
         if (_domImplementation == null) {
-            DocumentBuilderFactory dbf = FactoryImpl.getDOMFactory(_useServicesMechanism);
+            DocumentBuilderFactory dbf = JdkXmlUtils.getDOMFactory(_overrideDefaultParser);
             _domImplementation = dbf.newDocumentBuilder().getDOMImplementation();
         }
         return _domImplementation.createDocument(uri, qname, null);
--- a/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/runtime/output/TransletOutputHandlerFactory.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/runtime/output/TransletOutputHandlerFactory.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,6 @@
 /*
- * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2017, Oracle and/or its affiliates. All rights reserved.
+ * @LastModified: Oct 2017
  */
 /*
  * Licensed to the Apache Software Foundation (ASF) under one or more
@@ -70,17 +71,17 @@
     private ContentHandler _handler                 = null;
     private LexicalHandler _lexHandler              = null;
 
-    private boolean _useServicesMechanism;
+    private boolean _overrideDefaultParser;
 
     static public TransletOutputHandlerFactory newInstance() {
         return new TransletOutputHandlerFactory(true);
     }
-    static public TransletOutputHandlerFactory newInstance(boolean useServicesMechanism) {
-        return new TransletOutputHandlerFactory(useServicesMechanism);
+    static public TransletOutputHandlerFactory newInstance(boolean overrideDefaultParser) {
+        return new TransletOutputHandlerFactory(overrideDefaultParser);
     }
 
-    public TransletOutputHandlerFactory(boolean useServicesMechanism) {
-        _useServicesMechanism = useServicesMechanism;
+    public TransletOutputHandlerFactory(boolean overrideDefaultParser) {
+        _overrideDefaultParser = overrideDefaultParser;
     }
     public void setOutputType(int outputType) {
         _outputType = outputType;
@@ -195,7 +196,9 @@
                 return result;
 
             case DOM :
-                _handler = (_node != null) ? new SAX2DOM(_node, _nextSibling, _useServicesMechanism) : new SAX2DOM(_useServicesMechanism);
+                _handler = (_node != null) ?
+                        new SAX2DOM(_node, _nextSibling, _overrideDefaultParser) :
+                        new SAX2DOM(_overrideDefaultParser);
                 _lexHandler = (LexicalHandler) _handler;
                 // falls through
             case STAX :
--- a/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/trax/SAX2DOM.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/trax/SAX2DOM.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,6 @@
 /*
- * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2017, Oracle and/or its affiliates. All rights reserved.
+ * @LastModified: Oct 2017
  */
 /*
  * Licensed to the Apache Software Foundation (ASF) under one or more
@@ -25,15 +26,18 @@
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Stack;
-import javax.xml.parsers.DocumentBuilder;
+
 import javax.xml.parsers.DocumentBuilderFactory;
 import javax.xml.parsers.ParserConfigurationException;
+
+import com.sun.org.apache.xalan.internal.xsltc.runtime.Constants;
+import jdk.xml.internal.JdkXmlUtils;
+
 import org.w3c.dom.Comment;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 import org.w3c.dom.Node;
 import org.w3c.dom.ProcessingInstruction;
-import org.w3c.dom.Text;
 import org.xml.sax.Attributes;
 import org.xml.sax.ContentHandler;
 import org.xml.sax.Locator;
@@ -66,16 +70,16 @@
      * synchronization because the Javadoc is not explicit about
      * thread safety.
      */
-    private DocumentBuilderFactory _factory =
-            DocumentBuilderFactory.newInstance();
+    private DocumentBuilderFactory _factory;
     private boolean _internal = true;
 
-    public SAX2DOM(boolean useServicesMechanism) throws ParserConfigurationException {
-        _document = createDocument(useServicesMechanism);
+    public SAX2DOM(boolean overrideDefaultParser) throws ParserConfigurationException {
+        _document = createDocument(overrideDefaultParser);
         _root = _document;
     }
 
-    public SAX2DOM(Node root, Node nextSibling, boolean useServicesMechanism) throws ParserConfigurationException {
+    public SAX2DOM(Node root, Node nextSibling, boolean overrideDefaultParser)
+            throws ParserConfigurationException {
         _root = root;
         if (root instanceof Document) {
           _document = (Document)root;
@@ -84,15 +88,16 @@
           _document = root.getOwnerDocument();
         }
         else {
-          _document = createDocument(useServicesMechanism);
+          _document = createDocument(overrideDefaultParser);
           _root = _document;
         }
 
         _nextSibling = nextSibling;
     }
 
-    public SAX2DOM(Node root, boolean useServicesMechanism) throws ParserConfigurationException {
-        this(root, null, useServicesMechanism);
+    public SAX2DOM(Node root, boolean overrideDefaultParser)
+            throws ParserConfigurationException {
+        this(root, null, overrideDefaultParser);
     }
 
     public Node getDOM() {
@@ -304,18 +309,13 @@
     public void startDTD(String name, String publicId, String systemId)
         throws SAXException {}
 
-    private Document createDocument(boolean useServicesMechanism) throws ParserConfigurationException {
+    private Document createDocument(boolean overrideDefaultParser)
+            throws ParserConfigurationException {
         if (_factory == null) {
-            if (useServicesMechanism) {
-                _factory = DocumentBuilderFactory.newInstance();
-                if (!(_factory instanceof com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl)) {
-                    _internal = false;
-                }
-            } else {
-                _factory = DocumentBuilderFactory.newInstance(
-                  "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl",
-                  SAX2DOM.class.getClassLoader()
-                  );
+            _factory = JdkXmlUtils.getDOMFactory(overrideDefaultParser);
+            _internal = true;
+            if (!(_factory instanceof com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl)) {
+                _internal = false;
             }
         }
         Document doc;
--- a/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/trax/TemplatesHandlerImpl.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/trax/TemplatesHandlerImpl.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2017, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * Licensed to the Apache Software Foundation (ASF) under one or more
@@ -98,7 +98,7 @@
         _tfactory = tfactory;
 
         // Instantiate XSLTC and get reference to parser object
-        XSLTC xsltc = new XSLTC(tfactory.useServicesMechnism(), tfactory.getJdkXmlFeatures());
+        XSLTC xsltc = new XSLTC(tfactory.getJdkXmlFeatures());
         if (tfactory.getFeature(XMLConstants.FEATURE_SECURE_PROCESSING))
             xsltc.setSecureProcessing(true);
 
--- a/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/trax/TemplatesImpl.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/trax/TemplatesImpl.java	Fri Jan 19 09:32:10 2018 -0800
@@ -142,9 +142,9 @@
     private transient TransformerFactoryImpl _tfactory = null;
 
     /**
-     * A flag to determine whether the Service Mechanism is used
+     * A flag to determine whether the system-default parser may be overridden
      */
-    private transient boolean _useServicesMechanism;
+    private transient boolean _overrideDefaultParser;
 
     /**
      * protocols allowed for external references set by the stylesheet processing instruction, Import and Include element.
@@ -241,7 +241,7 @@
         _outputProperties = outputProperties;
         _indentNumber = indentNumber;
         _tfactory = tfactory;
-        _useServicesMechanism = tfactory.useServicesMechnism();
+        _overrideDefaultParser = tfactory.overrideDefaultParser();
         _accessExternalStylesheet = (String) tfactory.getAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET);
     }
     /**
@@ -324,8 +324,8 @@
     /**
      * Return the state of the services mechanism feature.
      */
-    public boolean useServicesMechnism() {
-        return _useServicesMechanism;
+    public boolean overrideDefaultParser() {
+        return _overrideDefaultParser;
     }
 
      /**
@@ -556,7 +556,7 @@
                     _class[_transletIndex].getConstructor().newInstance();
             translet.postInitialization();
             translet.setTemplates(this);
-            translet.setServicesMechnism(_useServicesMechanism);
+            translet.setOverrideDefaultParser(_overrideDefaultParser);
             translet.setAllowedProtocols(_accessExternalStylesheet);
             if (_auxClasses != null) {
                 translet.setAuxiliaryClasses(_auxClasses);
--- a/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/trax/TrAXFilter.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/trax/TrAXFilter.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2017, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * Licensed to the Apache Software Foundation (ASF) under one or more
@@ -23,11 +23,6 @@
 
 import java.io.IOException;
 
-import javax.xml.XMLConstants;
-import javax.xml.parsers.FactoryConfigurationError;
-import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.parsers.SAXParser;
-import javax.xml.parsers.SAXParserFactory;
 import javax.xml.transform.ErrorListener;
 import javax.xml.transform.Templates;
 import javax.xml.transform.Transformer;
@@ -35,13 +30,13 @@
 import javax.xml.transform.sax.SAXResult;
 
 import com.sun.org.apache.xml.internal.utils.XMLReaderManager;
+import jdk.xml.internal.JdkXmlUtils;
 
 import org.xml.sax.ContentHandler;
 import org.xml.sax.InputSource;
 import org.xml.sax.SAXException;
 import org.xml.sax.XMLReader;
 import org.xml.sax.helpers.XMLFilterImpl;
-import org.xml.sax.helpers.XMLReaderFactory;
 
 /**
  * skeleton extension of XMLFilterImpl for now.
@@ -53,7 +48,7 @@
     private Templates              _templates;
     private TransformerImpl        _transformer;
     private TransformerHandlerImpl _transformerHandler;
-    private boolean _useServicesMechanism = true;
+    private boolean _overrideDefaultParser;
 
     public TrAXFilter(Templates templates)  throws
         TransformerConfigurationException
@@ -61,7 +56,7 @@
         _templates = templates;
         _transformer = (TransformerImpl) templates.newTransformer();
         _transformerHandler = new TransformerHandlerImpl(_transformer);
-        _useServicesMechanism = _transformer.useServicesMechnism();
+        _overrideDefaultParser = _transformer.overrideDefaultParser();
     }
 
     public Transformer getTransformer() {
@@ -69,36 +64,14 @@
     }
 
     private void createParent() throws SAXException {
-        XMLReader parent = null;
-        try {
-            SAXParserFactory pfactory = SAXParserFactory.newInstance();
-            pfactory.setNamespaceAware(true);
-
-            if (_transformer.isSecureProcessing()) {
-                try {
-                    pfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
-                }
-                catch (SAXException e) {}
-            }
-
-            SAXParser saxparser = pfactory.newSAXParser();
-            parent = saxparser.getXMLReader();
-        }
-        catch (ParserConfigurationException e) {
-            throw new SAXException(e);
-        }
-        catch (FactoryConfigurationError e) {
-            throw new SAXException(e.toString());
-        }
-
-        if (parent == null) {
-            parent = XMLReaderFactory.createXMLReader();
-        }
+        XMLReader parent = JdkXmlUtils.getXMLReader(_overrideDefaultParser,
+                _transformer.isSecureProcessing());
 
         // make this XMLReader the parent of this filter
         setParent(parent);
     }
 
+    @Override
     public void parse (InputSource input) throws SAXException, IOException
     {
         XMLReader managedReader = null;
@@ -106,7 +79,7 @@
         try {
             if (getParent() == null) {
                 try {
-                    managedReader = XMLReaderManager.getInstance(_useServicesMechanism)
+                    managedReader = XMLReaderManager.getInstance(_overrideDefaultParser)
                                                     .getXMLReader();
                     setParent(managedReader);
                 } catch (SAXException  e) {
@@ -118,7 +91,7 @@
             getParent().parse(input);
         } finally {
             if (managedReader != null) {
-                XMLReaderManager.getInstance(_useServicesMechanism).releaseXMLReader(managedReader);
+                XMLReaderManager.getInstance(_overrideDefaultParser).releaseXMLReader(managedReader);
             }
         }
     }
--- a/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/trax/TransformerFactoryImpl.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/trax/TransformerFactoryImpl.java	Fri Jan 19 09:32:10 2018 -0800
@@ -21,7 +21,6 @@
 package com.sun.org.apache.xalan.internal.xsltc.trax;
 
 import com.sun.org.apache.xalan.internal.XalanConstants;
-import com.sun.org.apache.xalan.internal.utils.FactoryImpl;
 import com.sun.org.apache.xalan.internal.utils.FeaturePropertyBase;
 import com.sun.org.apache.xalan.internal.utils.ObjectFactory;
 import com.sun.org.apache.xalan.internal.utils.XMLSecurityManager;
@@ -55,15 +54,12 @@
 import javax.xml.catalog.CatalogFeatures;
 import javax.xml.catalog.CatalogManager;
 import javax.xml.catalog.CatalogResolver;
-import javax.xml.parsers.SAXParser;
-import javax.xml.parsers.SAXParserFactory;
 import javax.xml.transform.ErrorListener;
 import javax.xml.transform.Source;
 import javax.xml.transform.Templates;
 import javax.xml.transform.Transformer;
 import javax.xml.transform.TransformerConfigurationException;
 import javax.xml.transform.TransformerException;
-import javax.xml.transform.TransformerFactory;
 import javax.xml.transform.URIResolver;
 import javax.xml.transform.dom.DOMResult;
 import javax.xml.transform.dom.DOMSource;
@@ -79,18 +75,17 @@
 import jdk.xml.internal.JdkXmlUtils;
 import jdk.xml.internal.SecuritySupport;
 import org.xml.sax.InputSource;
+import org.xml.sax.SAXException;
 import org.xml.sax.XMLFilter;
 import org.xml.sax.XMLReader;
-import org.xml.sax.helpers.XMLReaderFactory;
 
 /**
- * Implementation of a JAXP1.1 TransformerFactory for Translets.
+ * Implementation of a JAXP TransformerFactory for Translets.
  * @author G. Todd Miller
  * @author Morten Jorgensen
  * @author Santiago Pericas-Geertsen
  * @LastModified: Nov 2017
  */
-@SuppressWarnings("deprecation") //org.xml.sax.helpers.XMLReaderFactory
 public class TransformerFactoryImpl
     extends SAXTransformerFactory implements SourceLoader, ErrorListener
 {
@@ -216,11 +211,11 @@
     private boolean _isSecureMode = false;
 
     /**
-     * Indicates whether implementation parts should use
-     *   service loader (or similar).
-     * Note the default value (false) is the safe option..
+     * Indicates whether 3rd party parser may be used to override the system-default
+     * Note the default value (false) is the safe option.
+     * Note same as the old property useServicesMechanism
      */
-    private boolean _useServicesMechanism;
+    private boolean _overrideDefaultParser;
 
     /**
      * protocols allowed for external references set by the stylesheet
@@ -259,15 +254,6 @@
      * javax.xml.transform.sax.TransformerFactory implementation.
      */
     public TransformerFactoryImpl() {
-        this(true);
-    }
-
-    public static TransformerFactory newTransformerFactoryNoServiceLoader() {
-        return new TransformerFactoryImpl(false);
-    }
-
-    private TransformerFactoryImpl(boolean useServicesMechanism) {
-        this._useServicesMechanism = useServicesMechanism;
 
         if (System.getSecurityManager() != null) {
             _isSecureMode = true;
@@ -275,6 +261,8 @@
         }
 
         _xmlFeatures = new JdkXmlFeatures(!_isNotSecureProcessing);
+        _overrideDefaultParser = _xmlFeatures.getFeature(
+                JdkXmlFeatures.XmlFeature.JDK_OVERRIDE_PARSER);
         _xmlSecurityPropertyMgr = new XMLSecurityPropertyManager();
         _accessExternalDTD = _xmlSecurityPropertyMgr.getValue(
                 Property.ACCESS_EXTERNAL_DTD);
@@ -594,14 +582,20 @@
                         JdkXmlFeatures.State.FSP, false);
             }
         }
-        else if (name.equals(XalanConstants.ORACLE_FEATURE_SERVICE_MECHANISM)) {
-            //in secure mode, let _useServicesMechanism be determined by the constructor
-            if (!_isSecureMode)
-                _useServicesMechanism = value;
-        }
         else {
+            if (name.equals(XalanConstants.ORACLE_FEATURE_SERVICE_MECHANISM)) {
+                // for compatibility, in secure mode, useServicesMechanism is determined by the constructor
+                if (_isSecureMode) {
+                    return;
+                }
+            }
             if (_xmlFeatures != null &&
                     _xmlFeatures.setFeature(name, JdkXmlFeatures.State.APIPROPERTY, value)) {
+                if (name.equals(JdkXmlUtils.OVERRIDE_PARSER) ||
+                        name.equals(JdkXmlFeatures.ORACLE_FEATURE_SERVICE_MECHANISM)) {
+                    _overrideDefaultParser = _xmlFeatures.getFeature(
+                            JdkXmlFeatures.XmlFeature.JDK_OVERRIDE_PARSER);
+                }
                 return;
             }
 
@@ -666,8 +660,8 @@
     /**
      * Return the state of the services mechanism feature.
      */
-    public boolean useServicesMechnism() {
-        return _useServicesMechanism;
+    public boolean overrideDefaultParser() {
+        return _overrideDefaultParser;
     }
 
      /**
@@ -726,10 +720,9 @@
         throws TransformerConfigurationException {
 
         String baseId;
-        XMLReader reader;
+        XMLReader reader = null;
         InputSource isource;
 
-
         /**
          * Fix for bugzilla bug 24187
          */
@@ -748,24 +741,15 @@
                 dom2sax.setContentHandler( _stylesheetPIHandler);
                 dom2sax.parse();
             } else {
+                if (source instanceof SAXSource) {
+                    reader = ((SAXSource)source).getXMLReader();
+                }
                 isource = SAXSource.sourceToInputSource(source);
                 baseId = isource.getSystemId();
 
-                SAXParserFactory factory = FactoryImpl.getSAXFactory(_useServicesMechanism);
-                factory.setNamespaceAware(true);
-
-                if (!_isNotSecureProcessing) {
-                    try {
-                        factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
-                    }
-                    catch (org.xml.sax.SAXException e) {}
-                }
-
-                SAXParser jaxpParser = factory.newSAXParser();
-
-                reader = jaxpParser.getXMLReader();
                 if (reader == null) {
-                    reader = XMLReaderFactory.createXMLReader();
+                    reader = JdkXmlUtils.getXMLReader(_overrideDefaultParser,
+                            !_isNotSecureProcessing);
                 }
 
                 _stylesheetPIHandler.setBaseId(baseId);
@@ -781,7 +765,7 @@
         } catch (StopParseException e ) {
           // startElement encountered so do not parse further
 
-        } catch (javax.xml.parsers.ParserConfigurationException | org.xml.sax.SAXException | IOException e) {
+        } catch (SAXException | IOException e) {
              throw new TransformerConfigurationException(
              "getAssociatedStylesheets failed", e);
         }
@@ -962,7 +946,7 @@
         }
 
         // Create and initialize a stylesheet compiler
-        final XSLTC xsltc = new XSLTC(_useServicesMechanism, _xmlFeatures);
+        final XSLTC xsltc = new XSLTC(_xmlFeatures);
         if (_debug) xsltc.setDebug(true);
         if (_enableInlining)
                 xsltc.setTemplateInlining(true);
--- a/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/trax/TransformerImpl.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/trax/TransformerImpl.java	Fri Jan 19 09:32:10 2018 -0800
@@ -21,7 +21,6 @@
 package com.sun.org.apache.xalan.internal.xsltc.trax;
 
 import com.sun.org.apache.xalan.internal.XalanConstants;
-import com.sun.org.apache.xalan.internal.utils.FactoryImpl;
 import com.sun.org.apache.xalan.internal.utils.XMLSecurityManager;
 import com.sun.org.apache.xalan.internal.xsltc.DOM;
 import com.sun.org.apache.xalan.internal.xsltc.DOMCache;
@@ -102,8 +101,6 @@
 
     private final static String LEXICAL_HANDLER_PROPERTY =
         "http://xml.org/sax/properties/lexical-handler";
-    private static final String NAMESPACE_FEATURE =
-        "http://xml.org/sax/features/namespaces";
 
     /**
      * Namespace prefixes feature for {@link XMLReader}.
@@ -200,15 +197,10 @@
     private boolean _isSecureProcessing = false;
 
     /**
-     * Indicates whether implementation parts should use
-     *   service loader (or similar).
-     * Note the default value (false) is the safe option..
+     * Indicates whether 3rd party parser may be used to override the system-default
      */
-    private boolean _useServicesMechanism;
-    /**
-     * protocols allowed for external references set by the stylesheet processing instruction, Import and Include element.
-     */
-    private String _accessExternalStylesheet = XalanConstants.EXTERNAL_ACCESS_DEFAULT;
+    private boolean _overrideDefaultParser;
+
      /**
      * protocols allowed for external DTD references in source file and/or stylesheet.
      */
@@ -276,11 +268,10 @@
         _propertiesClone = (Properties) _properties.clone();
         _indentNumber = indentNumber;
         _tfactory = tfactory;
-        _useServicesMechanism = _tfactory.useServicesMechnism();
-        _accessExternalStylesheet = (String)_tfactory.getAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET);
+        _overrideDefaultParser = _tfactory.overrideDefaultParser();
         _accessExternalDTD = (String)_tfactory.getAttribute(XMLConstants.ACCESS_EXTERNAL_DTD);
         _securityManager = (XMLSecurityManager)_tfactory.getAttribute(XalanConstants.SECURITY_MANAGER);
-        _readerManager = XMLReaderManager.getInstance(_useServicesMechanism);
+        _readerManager = XMLReaderManager.getInstance(_overrideDefaultParser);
         _readerManager.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, _accessExternalDTD);
         _readerManager.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, _isSecureProcessing);
         _readerManager.setProperty(XalanConstants.SECURITY_MANAGER, _securityManager);
@@ -317,15 +308,15 @@
     /**
      * Return the state of the services mechanism feature.
      */
-    public boolean useServicesMechnism() {
-        return _useServicesMechanism;
+    public boolean overrideDefaultParser() {
+        return _overrideDefaultParser;
     }
 
     /**
      * Set the state of the services mechanism feature.
      */
-    public void setServicesMechnism(boolean flag) {
-        _useServicesMechanism = flag;
+    public void setOverrideDefaultParser(boolean flag) {
+        _overrideDefaultParser = flag;
     }
 
     /**
@@ -409,7 +400,7 @@
         // Get encoding using getProperty() to use defaults
         _encoding = _properties.getProperty(OutputKeys.ENCODING);
 
-        _tohFactory = TransletOutputHandlerFactory.newInstance(_useServicesMechanism);
+        _tohFactory = TransletOutputHandlerFactory.newInstance(_overrideDefaultParser);
         _tohFactory.setEncoding(_encoding);
         if (_method != null) {
             _tohFactory.setOutputMethod(_method);
@@ -579,7 +570,7 @@
                  if (_dtmManager == null) {
                      _dtmManager =
                          _tfactory.createNewDTMManagerInstance();
-                     _dtmManager.setServicesMechnism(_useServicesMechanism);
+                     _dtmManager.setOverrideDefaultParser(_overrideDefaultParser);
                  }
                  dom = (DOM)_dtmManager.getDTM(source, false, wsfilter, true,
                                               false, false, 0, hasIdCall);
@@ -754,7 +745,7 @@
 
                 boolean supportCatalog = true;
 
-                DocumentBuilderFactory builderF = FactoryImpl.getDOMFactory(_useServicesMechanism);
+                DocumentBuilderFactory builderF = JdkXmlUtils.getDOMFactory(_overrideDefaultParser);
                 try {
                     builderF.setFeature(XMLConstants.USE_CATALOG, _useCatalog);
                 } catch (ParserConfigurationException e) {
--- a/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/trax/Util.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/trax/Util.java	Fri Jan 19 09:32:10 2018 -0800
@@ -21,7 +21,6 @@
 package com.sun.org.apache.xalan.internal.xsltc.trax;
 
 import com.sun.org.apache.xalan.internal.XalanConstants;
-import com.sun.org.apache.xalan.internal.utils.FactoryImpl;
 import com.sun.org.apache.xalan.internal.utils.XMLSecurityManager;
 import com.sun.org.apache.xalan.internal.xsltc.compiler.XSLTC;
 import com.sun.org.apache.xalan.internal.xsltc.compiler.util.ErrorMsg;
@@ -30,8 +29,6 @@
 import javax.xml.XMLConstants;
 import javax.xml.catalog.CatalogFeatures;
 import javax.xml.catalog.CatalogFeatures.Feature;
-import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.parsers.SAXParserFactory;
 import javax.xml.stream.XMLEventReader;
 import javax.xml.stream.XMLStreamReader;
 import javax.xml.transform.Source;
@@ -42,13 +39,13 @@
 import javax.xml.transform.stream.StreamSource;
 import jdk.xml.internal.JdkXmlFeatures;
 import jdk.xml.internal.JdkXmlUtils;
+import jdk.xml.internal.SecuritySupport;
 import org.w3c.dom.Document;
 import org.xml.sax.InputSource;
 import org.xml.sax.SAXException;
 import org.xml.sax.SAXNotRecognizedException;
 import org.xml.sax.SAXNotSupportedException;
 import org.xml.sax.XMLReader;
-import org.xml.sax.helpers.XMLReaderFactory;
 
 /**
  * @author Santiago Pericas-Geertsen
@@ -57,6 +54,7 @@
  */
 @SuppressWarnings("deprecation") //org.xml.sax.helpers.XMLReaderFactory
 public final class Util {
+    private static final String property = "org.xml.sax.driver";
 
     public static String baseName(String name) {
         return com.sun.org.apache.xalan.internal.xsltc.compiler.util.Util.baseName(name);
@@ -89,54 +87,18 @@
                 try {
                     XMLReader reader = sax.getXMLReader();
 
-                     /*
-                      * Fix for bug 24695
-                      * According to JAXP 1.2 specification if a SAXSource
-                      * is created using a SAX InputSource the Transformer or
-                      * TransformerFactory creates a reader via the
-                      * XMLReaderFactory if setXMLReader is not used
-                      */
-
                     if (reader == null) {
-                       try {
-                           reader= XMLReaderFactory.createXMLReader();
-                           try {
-                                reader.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING,
-                                            xsltc.isSecureProcessing());
-                           } catch (SAXNotRecognizedException e) {
-                                XMLSecurityManager.printWarning(reader.getClass().getName(),
-                                        XMLConstants.FEATURE_SECURE_PROCESSING, e);
-                           }
-                       } catch (Exception e ) {
-                           try {
-
-                               //Incase there is an exception thrown
-                               // resort to JAXP
-                               SAXParserFactory parserFactory = FactoryImpl.getSAXFactory(xsltc.useServicesMechnism());
-                               parserFactory.setNamespaceAware(true);
-
-                               if (xsltc.isSecureProcessing()) {
-                                  try {
-                                      parserFactory.setFeature(
-                                          XMLConstants.FEATURE_SECURE_PROCESSING, true);
-                                  }
-                                  catch (org.xml.sax.SAXException se) {}
-                               }
-
-                               reader = parserFactory.newSAXParser()
-                                     .getXMLReader();
-
-
-                           } catch (ParserConfigurationException pce ) {
-                               throw new TransformerConfigurationException
-                                 ("ParserConfigurationException" ,pce);
-                           }
-                       }
+                        boolean overrideDefaultParser = xsltc.getFeature(
+                                JdkXmlFeatures.XmlFeature.JDK_OVERRIDE_PARSER);
+                        reader = JdkXmlUtils.getXMLReader(overrideDefaultParser,
+                                xsltc.isSecureProcessing());
+                    } else {
+                        // compatibility for legacy applications
+                        reader.setFeature
+                            (JdkXmlUtils.NAMESPACES_FEATURE,true);
+                        reader.setFeature
+                            (JdkXmlUtils.NAMESPACE_PREFIXES_FEATURE,false);
                     }
-                    reader.setFeature
-                        ("http://xml.org/sax/features/namespaces",true);
-                    reader.setFeature
-                        ("http://xml.org/sax/features/namespace-prefixes",false);
 
                     JdkXmlUtils.setXMLReaderPropertyIfSupport(reader, XMLConstants.ACCESS_EXTERNAL_DTD,
                             xsltc.getProperty(XMLConstants.ACCESS_EXTERNAL_DTD), true);
@@ -192,9 +154,6 @@
                 }catch (SAXNotSupportedException snse ) {
                   throw new TransformerConfigurationException
                        ("SAXNotSupportedException ",snse);
-                }catch (SAXException se ) {
-                  throw new TransformerConfigurationException
-                       ("SAXException ",se);
                 }
 
             }
--- a/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/dom/DOMConfigurationImpl.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/dom/DOMConfigurationImpl.java	Fri Jan 19 09:32:10 2018 -0800
@@ -259,7 +259,8 @@
             SEND_PSVI,
             NAMESPACE_GROWTH,
             TOLERATE_DUPLICATES,
-            XMLConstants.USE_CATALOG
+            XMLConstants.USE_CATALOG,
+            JdkXmlUtils.OVERRIDE_PARSER
         };
         addRecognizedFeatures(recognizedFeatures);
 
@@ -273,6 +274,7 @@
         setFeature(SEND_PSVI, true);
         setFeature(NAMESPACE_GROWTH, false);
         setFeature(XMLConstants.USE_CATALOG, JdkXmlUtils.USE_CATALOG_DEFAULT);
+        setFeature(JdkXmlUtils.OVERRIDE_PARSER, JdkXmlUtils.OVERRIDE_PARSER_DEFAULT);
 
         // add default recognized properties
         final String[] recognizedProperties = {
--- a/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages.properties	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages.properties	Fri Jan 19 09:32:10 2018 -0800
@@ -304,4 +304,5 @@
         EntityReplacementLimit=JAXP00010007: The total number of nodes in entity references is \"{0}\" that is over the limit \"{1}\" set by \"{2}\".
 
 # Catalog 09
-        CatalogException=JAXP00090001: The CatalogResolver is enabled with the catalog \"{0}\", but a CatalogException is returned.
\ No newline at end of file
+# Technical term, do not translate: catalog
+        CatalogException=JAXP00090001: The CatalogResolver is enabled with the catalog \"{0}\", but a CatalogException is returned.
--- a/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XMLSchemaLoader.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XMLSchemaLoader.java	Fri Jan 19 09:32:10 2018 -0800
@@ -75,6 +75,7 @@
 import java.util.StringTokenizer;
 import java.util.WeakHashMap;
 import javax.xml.XMLConstants;
+import jdk.xml.internal.JdkXmlFeatures;
 import jdk.xml.internal.JdkXmlUtils;
 import jdk.xml.internal.SecuritySupport;
 import org.w3c.dom.DOMConfiguration;
@@ -160,7 +161,7 @@
     protected static final String SCHEMA_DV_FACTORY =
         Constants.XERCES_PROPERTY_PREFIX + Constants.SCHEMA_DV_FACTORY_PROPERTY;
 
-    protected static final String USE_SERVICE_MECHANISM = Constants.ORACLE_FEATURE_SERVICE_MECHANISM;
+    protected static final String OVERRIDE_PARSER = JdkXmlUtils.OVERRIDE_PARSER;
 
     // recognized features:
     private static final String[] RECOGNIZED_FEATURES = {
@@ -175,7 +176,7 @@
         HONOUR_ALL_SCHEMALOCATIONS,
         NAMESPACE_GROWTH,
         TOLERATE_DUPLICATES,
-        USE_SERVICE_MECHANISM,
+        OVERRIDE_PARSER,
         XMLConstants.USE_CATALOG
     };
 
@@ -313,18 +314,14 @@
      * @param sHandler
      * @param builder
      */
-    XMLSchemaLoader(XMLErrorReporter errorReporter,
-            XSGrammarBucket grammarBucket,
+    XMLSchemaLoader(XMLErrorReporter errorReporter, XSGrammarBucket grammarBucket,
             SubstitutionGroupHandler sHandler, CMBuilder builder) {
         this(null, errorReporter, null, grammarBucket, sHandler, builder);
     }
 
-    XMLSchemaLoader(SymbolTable symbolTable,
-            XMLErrorReporter errorReporter,
-            XMLEntityManager entityResolver,
-            XSGrammarBucket grammarBucket,
-            SubstitutionGroupHandler sHandler,
-            CMBuilder builder) {
+    XMLSchemaLoader(SymbolTable symbolTable, XMLErrorReporter errorReporter,
+            XMLEntityManager entityResolver, XSGrammarBucket grammarBucket,
+            SubstitutionGroupHandler sHandler, CMBuilder builder) {
 
         // store properties and features in configuration
         fLoaderConfig.addRecognizedFeatures(RECOGNIZED_FEATURES);
@@ -1231,7 +1228,7 @@
                 name.equals(HONOUR_ALL_SCHEMALOCATIONS) ||
                 name.equals(NAMESPACE_GROWTH) ||
                 name.equals(TOLERATE_DUPLICATES) ||
-                name.equals(USE_SERVICE_MECHANISM)) {
+                name.equals(OVERRIDE_PARSER)) {
                 return true;
 
             }
@@ -1310,7 +1307,7 @@
             v.add(HONOUR_ALL_SCHEMALOCATIONS);
             v.add(NAMESPACE_GROWTH);
             v.add(TOLERATE_DUPLICATES);
-            v.add(USE_SERVICE_MECHANISM);
+            v.add(OVERRIDE_PARSER);
             fRecognizedParameters = new DOMStringListImpl(v);
         }
         return fRecognizedParameters;
--- a/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XMLSchemaValidator.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XMLSchemaValidator.java	Fri Jan 19 09:32:10 2018 -0800
@@ -265,7 +265,7 @@
     private static final String XML_SECURITY_PROPERTY_MANAGER =
             Constants.XML_SECURITY_PROPERTY_MANAGER;
 
-    protected static final String USE_SERVICE_MECHANISM = Constants.ORACLE_FEATURE_SERVICE_MECHANISM;
+    protected static final String OVERRIDE_PARSER = JdkXmlUtils.OVERRIDE_PARSER;
 
     protected static final String USE_CATALOG = XMLConstants.USE_CATALOG;
 
@@ -291,8 +291,8 @@
             UNPARSED_ENTITY_CHECKING,
             NAMESPACE_GROWTH,
             TOLERATE_DUPLICATES,
-            USE_SERVICE_MECHANISM,
-            USE_CATALOG
+            OVERRIDE_PARSER,
+            USE_CATALOG,
         };
 
     /** Feature defaults. */
@@ -323,7 +323,7 @@
         null,
         null,
         null,
-        Boolean.TRUE,
+        JdkXmlUtils.OVERRIDE_PARSER_DEFAULT,
         JdkXmlUtils.USE_CATALOG_DEFAULT
     };
 
--- a/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/opti/SchemaParsingConfig.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/opti/SchemaParsingConfig.java	Fri Jan 19 09:32:10 2018 -0800
@@ -304,7 +304,8 @@
             ALLOW_JAVA_ENCODINGS,       CONTINUE_AFTER_FATAL_ERROR,
             LOAD_EXTERNAL_DTD,          NOTIFY_BUILTIN_REFS,
             NOTIFY_CHAR_REFS, GENERATE_SYNTHETIC_ANNOTATIONS,
-            XMLConstants.USE_CATALOG
+            XMLConstants.USE_CATALOG,
+            JdkXmlUtils.OVERRIDE_PARSER
         };
         addRecognizedFeatures(recognizedFeatures);
         fFeatures.put(PARSER_SETTINGS, Boolean.TRUE);
@@ -319,6 +320,7 @@
         fFeatures.put(NOTIFY_CHAR_REFS, Boolean.FALSE);
         fFeatures.put(GENERATE_SYNTHETIC_ANNOTATIONS, Boolean.FALSE);
         fFeatures.put(XMLConstants.USE_CATALOG, JdkXmlUtils.USE_CATALOG_DEFAULT);
+        fFeatures.put(JdkXmlUtils.OVERRIDE_PARSER, JdkXmlUtils.OVERRIDE_PARSER_DEFAULT);
 
         // add default recognized properties
         final String[] recognizedProperties = {
--- a/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/traversers/XSDHandler.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/traversers/XSDHandler.java	Fri Jan 19 09:32:10 2018 -0800
@@ -115,7 +115,6 @@
 import org.xml.sax.SAXNotRecognizedException;
 import org.xml.sax.SAXParseException;
 import org.xml.sax.XMLReader;
-import org.xml.sax.helpers.XMLReaderFactory;
 
 /**
  * The purpose of this class is to co-ordinate the construction of a
@@ -422,6 +421,8 @@
     private String fPrefer;
     private String fResolve;
 
+    private boolean fOverrideDefaultParser;
+
     //************ Traversers **********
     XSDAttributeGroupTraverser fAttributeGroupTraverser;
     XSDAttributeTraverser fAttributeTraverser;
@@ -2244,7 +2245,8 @@
                 XSDKey key = null;
                 String schemaId = null;
                 if (referType != XSDDescription.CONTEXT_PREPARSE) {
-                    schemaId = XMLEntityManager.expandSystemId(inputSource.getSystemId(), schemaSource.getBaseSystemId(), false);
+                    schemaId = XMLEntityManager.expandSystemId(inputSource.getSystemId(),
+                            schemaSource.getBaseSystemId(), false);
                     key = new XSDKey(schemaId, referType, schemaNamespace);
                     if ((schemaElement = fTraversed.get(key)) != null) {
                         fLastSchemaWasDuplicate = true;
@@ -2260,17 +2262,10 @@
                     catch (SAXException se) {}
                 }
                 else {
+                    parser = JdkXmlUtils.getXMLReader(fOverrideDefaultParser,
+                            fSecurityManager.isSecureProcessing());
+
                     try {
-                        parser = XMLReaderFactory.createXMLReader();
-                    }
-                    // If something went wrong with the factory
-                    // just use our own SAX parser.
-                    catch (SAXException se) {
-                        parser = new SAXParser();
-                    }
-                    try {
-                        parser.setFeature(NAMESPACE_PREFIXES, true);
-                        namespacePrefixes = true;
                         // If this is a Xerces SAX parser set the security manager if there is one
                         if (parser instanceof SAXParser) {
                             if (fSecurityManager != null) {
@@ -3629,6 +3624,9 @@
         fAccessExternalSchema = fSecurityPropertyMgr.getValue(
                 XMLSecurityPropertyManager.Property.ACCESS_EXTERNAL_SCHEMA);
 
+        fOverrideDefaultParser = componentManager.getFeature(JdkXmlUtils.OVERRIDE_PARSER);
+        fSchemaParser.setFeature(JdkXmlUtils.OVERRIDE_PARSER, fOverrideDefaultParser);
+        fEntityManager.setFeature(JdkXmlUtils.OVERRIDE_PARSER, fOverrideDefaultParser);
         // Passing the Catalog settings to the parser
         fUseCatalog = componentManager.getFeature(XMLConstants.USE_CATALOG);
         fSchemaParser.setFeature(XMLConstants.USE_CATALOG, fUseCatalog);
--- a/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/jaxp/validation/DOMValidatorHelper.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/jaxp/validation/DOMValidatorHelper.java	Fri Jan 19 09:32:10 2018 -0800
@@ -45,6 +45,7 @@
 import javax.xml.transform.Source;
 import javax.xml.transform.dom.DOMResult;
 import javax.xml.transform.dom.DOMSource;
+import jdk.xml.internal.JdkXmlUtils;
 import org.w3c.dom.Attr;
 import org.w3c.dom.CDATASection;
 import org.w3c.dom.Comment;
@@ -380,9 +381,8 @@
         }
         if (result.getNode() == null) {
             try {
-                DocumentBuilderFactory factory = fComponentManager.getFeature(Constants.ORACLE_FEATURE_SERVICE_MECHANISM) ?
-                                    DocumentBuilderFactory.newInstance() : new DocumentBuilderFactoryImpl();
-                factory.setNamespaceAware(true);
+                DocumentBuilderFactory factory = JdkXmlUtils.getDOMFactory(
+                        fComponentManager.getFeature(JdkXmlUtils.OVERRIDE_PARSER));
                 DocumentBuilder builder = factory.newDocumentBuilder();
                 result.setNode(builder.newDocument());
             }
--- a/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/jaxp/validation/StAXValidatorHelper.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/jaxp/validation/StAXValidatorHelper.java	Fri Jan 19 09:32:10 2018 -0800
@@ -25,6 +25,7 @@
 
 package com.sun.org.apache.xerces.internal.jaxp.validation;
 
+import com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl;
 import com.sun.org.apache.xerces.internal.impl.Constants;
 import com.sun.org.apache.xerces.internal.utils.XMLSecurityManager;
 import java.io.IOException;
@@ -41,6 +42,7 @@
 import javax.xml.transform.sax.TransformerHandler;
 import javax.xml.transform.stax.StAXResult;
 import javax.xml.transform.stax.StAXSource;
+import jdk.xml.internal.JdkXmlUtils;
 
 import org.xml.sax.SAXException;
 
@@ -50,7 +52,6 @@
  * @author Sunitha Reddy
  */
 public final class StAXValidatorHelper implements ValidatorHelper {
-    private static final String DEFAULT_TRANSFORMER_IMPL = "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl";
 
     /** Component manager. **/
     private XMLSchemaValidatorComponentManager fComponentManager;
@@ -71,10 +72,11 @@
 
             if( identityTransformer1==null ) {
                 try {
-                    SAXTransformerFactory tf = fComponentManager.getFeature(Constants.ORACLE_FEATURE_SERVICE_MECHANISM) ?
-                                    (SAXTransformerFactory)SAXTransformerFactory.newInstance()
-                                    : (SAXTransformerFactory) TransformerFactory.newInstance(DEFAULT_TRANSFORMER_IMPL, StAXValidatorHelper.class.getClassLoader());
-                    XMLSecurityManager securityManager = (XMLSecurityManager)fComponentManager.getProperty(Constants.SECURITY_MANAGER);
+                    SAXTransformerFactory tf = JdkXmlUtils.getSAXTransformFactory(
+                            fComponentManager.getFeature(JdkXmlUtils.OVERRIDE_PARSER));
+
+                    XMLSecurityManager securityManager =
+                            (XMLSecurityManager)fComponentManager.getProperty(Constants.SECURITY_MANAGER);
                     if (securityManager != null) {
                         for (XMLSecurityManager.Limit limit : XMLSecurityManager.Limit.values()) {
                             if (securityManager.isSet(limit.ordinal())){
--- a/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/jaxp/validation/StreamValidatorHelper.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/jaxp/validation/StreamValidatorHelper.java	Fri Jan 19 09:32:10 2018 -0800
@@ -98,9 +98,6 @@
     private static final String VALIDATION_MANAGER
             = Constants.XERCES_PROPERTY_PREFIX + Constants.VALIDATION_MANAGER_PROPERTY;
 
-    private static final String DEFAULT_TRANSFORMER_IMPL
-            = "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl";
-
     /**
      * Property id: security manager.
      */
@@ -141,12 +138,9 @@
 
             if (result != null) {
                 try {
-                    SAXTransformerFactory tf = fComponentManager.getFeature(
-                            Constants.ORACLE_FEATURE_SERVICE_MECHANISM) ?
-                            (SAXTransformerFactory) SAXTransformerFactory.newInstance() :
-                            (SAXTransformerFactory) TransformerFactory.newInstance(
-                                    DEFAULT_TRANSFORMER_IMPL,
-                                    StreamValidatorHelper.class.getClassLoader());
+                    SAXTransformerFactory tf = JdkXmlUtils.getSAXTransformFactory(
+                            fComponentManager.getFeature(JdkXmlUtils.OVERRIDE_PARSER));
+
                     identityTransformerHandler = tf.newTransformerHandler();
                 } catch (TransformerConfigurationException e) {
                     throw new TransformerFactoryConfigurationError(e);
--- a/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/jaxp/validation/ValidatorHandlerImpl.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/jaxp/validation/ValidatorHandlerImpl.java	Fri Jan 19 09:32:10 2018 -0800
@@ -675,16 +675,14 @@
                 XMLReader reader = saxSource.getXMLReader();
                 if( reader==null ) {
                     // create one now
-                    SAXParserFactory spf = fComponentManager.getFeature(Constants.ORACLE_FEATURE_SERVICE_MECHANISM) ?
-                                    SAXParserFactory.newInstance() : new SAXParserFactoryImpl();
-                    spf.setNamespaceAware(true);
+                    reader = JdkXmlUtils.getXMLReader(fComponentManager.getFeature(JdkXmlUtils.OVERRIDE_PARSER),
+                            fComponentManager.getFeature(XMLConstants.FEATURE_SECURE_PROCESSING));
+
                     try {
-                        spf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING,
-                                fComponentManager.getFeature(XMLConstants.FEATURE_SECURE_PROCESSING));
-                        reader = spf.newSAXParser().getXMLReader();
                         // If this is a Xerces SAX parser, set the security manager if there is one
                         if (reader instanceof com.sun.org.apache.xerces.internal.parsers.SAXParser) {
-                           XMLSecurityManager securityManager = (XMLSecurityManager) fComponentManager.getProperty(SECURITY_MANAGER);
+                           XMLSecurityManager securityManager =
+                                   (XMLSecurityManager) fComponentManager.getProperty(SECURITY_MANAGER);
                            if (securityManager != null) {
                                try {
                                    reader.setProperty(SECURITY_MANAGER, securityManager);
--- a/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/jaxp/validation/XMLSchemaFactory.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/jaxp/validation/XMLSchemaFactory.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2017, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * Licensed to the Apache Software Foundation (ASF) under one or more
@@ -51,6 +51,7 @@
 import javax.xml.transform.stream.StreamSource;
 import javax.xml.validation.Schema;
 import javax.xml.validation.SchemaFactory;
+import jdk.xml.internal.JdkXmlFeatures;
 import jdk.xml.internal.JdkXmlUtils;
 import org.w3c.dom.Node;
 import org.w3c.dom.ls.LSResourceResolver;
@@ -127,22 +128,16 @@
     /** Whether or not to allow new schemas to be added to the grammar pool */
     private boolean fUseGrammarPoolOnly;
 
+    private final JdkXmlFeatures fXmlFeatures;
     /**
-     * Indicates whether implementation parts should use
-     *   service loader (or similar).
-     * Note the default value (false) is the safe option..
+     * Indicates whether 3rd party parser may be used to override the system-default
+     * Note the default value (false) is the safe option.
+     * Note same as the old property useServicesMechanism
      */
-    private final boolean fUseServicesMechanism;
+    private final boolean fOverrideDefaultParser;
 
 
     public XMLSchemaFactory() {
-        this(true);
-    }
-    public static XMLSchemaFactory newXMLSchemaFactoryNoServiceLoader() {
-        return new XMLSchemaFactory(false);
-    }
-    private XMLSchemaFactory(boolean useServicesMechanism) {
-        fUseServicesMechanism = useServicesMechanism;
         fErrorHandlerWrapper = new ErrorHandlerWrapper(DraconianErrorHandler.getInstance());
         fDOMEntityResolverWrapper = new DOMEntityResolverWrapper();
         fXMLGrammarPoolWrapper = new XMLGrammarPoolWrapper();
@@ -167,6 +162,10 @@
         }
 
         fXMLSchemaLoader.setProperty(JdkXmlUtils.CDATA_CHUNK_SIZE, JdkXmlUtils.CDATA_CHUNK_SIZE_DEFAULT);
+        fXmlFeatures = new JdkXmlFeatures(fSecurityManager.isSecureProcessing());
+        fOverrideDefaultParser = fXmlFeatures.getFeature(
+                JdkXmlFeatures.XmlFeature.JDK_OVERRIDE_PARSER);
+        fXMLSchemaLoader.setFeature(JdkXmlUtils.OVERRIDE_PARSER, fOverrideDefaultParser);
     }
 
     /**
@@ -363,6 +362,11 @@
         else if (name.equals(USE_GRAMMAR_POOL_ONLY)) {
             return fUseGrammarPoolOnly;
         }
+        /** Check to see if the property is managed by the JdkXmlFeatues **/
+        int index = fXmlFeatures.getIndex(name);
+        if (index > -1) {
+            return fXmlFeatures.getFeature(index);
+        }
         try {
             return fXMLSchemaLoader.getFeature(name);
         }
@@ -452,10 +456,20 @@
             return;
         }
         else if (name.equals(Constants.ORACLE_FEATURE_SERVICE_MECHANISM)) {
-            //in secure mode, let _useServicesMechanism be determined by the constructor
+            //in secure mode, let useServicesMechanism be determined by the constructor
             if (System.getSecurityManager() != null)
                 return;
         }
+
+        if ((fXmlFeatures != null) &&
+                    fXmlFeatures.setFeature(name, JdkXmlFeatures.State.APIPROPERTY, value)) {
+            if (name.equals(JdkXmlUtils.OVERRIDE_PARSER)
+                    || name.equals(Constants.ORACLE_FEATURE_SERVICE_MECHANISM)
+                    || name.equals(JdkXmlUtils.USE_CATALOG)) {
+                fXMLSchemaLoader.setFeature(name, value);
+            }
+            return;
+        }
         try {
             fXMLSchemaLoader.setFeature(name, value);
         }
@@ -528,7 +542,7 @@
     private void propagateFeatures(AbstractXMLSchema schema) {
         schema.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING,
                 (fSecurityManager != null && fSecurityManager.isSecureProcessing()));
-        schema.setFeature(Constants.ORACLE_FEATURE_SERVICE_MECHANISM, fUseServicesMechanism);
+        schema.setFeature(JdkXmlUtils.OVERRIDE_PARSER, fOverrideDefaultParser);
         String[] features = fXMLSchemaLoader.getRecognizedFeatures();
         for (int i = 0; i < features.length; ++i) {
             boolean state = fXMLSchemaLoader.getFeature(features[i]);
--- a/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/jaxp/validation/XMLSchemaValidatorComponentManager.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/jaxp/validation/XMLSchemaValidatorComponentManager.java	Fri Jan 19 09:32:10 2018 -0800
@@ -264,7 +264,8 @@
                 NORMALIZE_DATA,
                 SCHEMA_ELEMENT_DEFAULT,
                 SCHEMA_AUGMENT_PSVI,
-                XMLConstants.USE_CATALOG
+                XMLConstants.USE_CATALOG,
+                JdkXmlUtils.OVERRIDE_PARSER
         };
         addRecognizedFeatures(recognizedFeatures);
         fFeatures.put(DISALLOW_DOCTYPE_DECL_FEATURE, Boolean.FALSE);
@@ -272,6 +273,7 @@
         fFeatures.put(SCHEMA_ELEMENT_DEFAULT, Boolean.FALSE);
         fFeatures.put(SCHEMA_AUGMENT_PSVI, Boolean.TRUE);
         fFeatures.put(XMLConstants.USE_CATALOG, grammarContainer.getFeature(XMLConstants.USE_CATALOG));
+        fFeatures.put(JdkXmlUtils.OVERRIDE_PARSER, grammarContainer.getFeature(JdkXmlUtils.OVERRIDE_PARSER));
 
         addRecognizedParamsAndSetDefaults(fEntityManager, grammarContainer);
         addRecognizedParamsAndSetDefaults(fErrorReporter, grammarContainer);
--- a/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/parsers/DTDConfiguration.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/parsers/DTDConfiguration.java	Fri Jan 19 09:32:10 2018 -0800
@@ -310,7 +310,8 @@
             //NOTIFY_BUILTIN_REFS,  // from XMLDocumentFragmentScannerImpl
             //NOTIFY_CHAR_REFS,         // from XMLDocumentFragmentScannerImpl
             //WARN_ON_DUPLICATE_ENTITYDEF,  // from XMLEntityManager
-            XMLConstants.USE_CATALOG
+            XMLConstants.USE_CATALOG,
+            JdkXmlUtils.OVERRIDE_PARSER
         };
         addRecognizedFeatures(recognizedFeatures);
 
@@ -324,6 +325,7 @@
         //setFeature(NOTIFY_CHAR_REFS, false);      // from XMLDocumentFragmentScannerImpl
         //setFeature(WARN_ON_DUPLICATE_ENTITYDEF, false);   // from XMLEntityManager
         fFeatures.put(XMLConstants.USE_CATALOG, JdkXmlUtils.USE_CATALOG_DEFAULT);
+        fFeatures.put(JdkXmlUtils.OVERRIDE_PARSER, JdkXmlUtils.OVERRIDE_PARSER_DEFAULT);
 
         // add default recognized properties
         final String[] recognizedProperties = {
--- a/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/parsers/NonValidatingConfiguration.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/parsers/NonValidatingConfiguration.java	Fri Jan 19 09:32:10 2018 -0800
@@ -294,7 +294,8 @@
             //NOTIFY_BUILTIN_REFS,  // from XMLDocumentFragmentScannerImpl
             //NOTIFY_CHAR_REFS,         // from XMLDocumentFragmentScannerImpl
             //WARN_ON_DUPLICATE_ENTITYDEF   // from XMLEntityManager
-            XMLConstants.USE_CATALOG
+            XMLConstants.USE_CATALOG,
+            JdkXmlUtils.OVERRIDE_PARSER
         };
         addRecognizedFeatures(recognizedFeatures);
 
@@ -310,6 +311,7 @@
         //setFeature(NOTIFY_CHAR_REFS, false);      // from XMLDocumentFragmentScannerImpl
         //setFeature(WARN_ON_DUPLICATE_ENTITYDEF, false);   // from XMLEntityManager
         fFeatures.put(XMLConstants.USE_CATALOG, JdkXmlUtils.USE_CATALOG_DEFAULT);
+        fFeatures.put(JdkXmlUtils.OVERRIDE_PARSER, JdkXmlUtils.OVERRIDE_PARSER_DEFAULT);
 
         // add default recognized properties
         final String[] recognizedProperties = {
--- a/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/parsers/XML11Configuration.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/parsers/XML11Configuration.java	Fri Jan 19 09:32:10 2018 -0800
@@ -508,7 +508,8 @@
             PARSER_SETTINGS,
             XMLConstants.FEATURE_SECURE_PROCESSING,
             XMLConstants.USE_CATALOG,
-            JdkXmlUtils.RESET_SYMBOL_TABLE
+            JdkXmlUtils.RESET_SYMBOL_TABLE,
+            JdkXmlUtils.OVERRIDE_PARSER
         };
         addRecognizedFeatures(recognizedFeatures);
         // set state for default features
@@ -535,6 +536,7 @@
         fFeatures.put(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
         fFeatures.put(XMLConstants.USE_CATALOG, JdkXmlUtils.USE_CATALOG_DEFAULT);
         fFeatures.put(JdkXmlUtils.RESET_SYMBOL_TABLE, JdkXmlUtils.RESET_SYMBOL_TABLE_DEFAULT);
+        fFeatures.put(JdkXmlUtils.OVERRIDE_PARSER, JdkXmlUtils.OVERRIDE_PARSER_DEFAULT);
 
         // add default recognized properties
         final String[] recognizedProperties =
--- a/src/java.xml/share/classes/com/sun/org/apache/xml/internal/dtm/DTMManager.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.xml/share/classes/com/sun/org/apache/xml/internal/dtm/DTMManager.java	Fri Jan 19 09:32:10 2018 -0800
@@ -52,7 +52,7 @@
    */
   protected XMLStringFactory m_xsf = null;
 
-  private boolean _useServicesMechanism;
+  private boolean _overrideDefaultParser;
   /**
    * Default constructor is protected on purpose.
    */
@@ -297,15 +297,15 @@
     /**
      * Return the state of the services mechanism feature.
      */
-    public boolean useServicesMechnism() {
-        return _useServicesMechanism;
+    public boolean overrideDefaultParser() {
+        return _overrideDefaultParser;
     }
 
     /**
      * Set the state of the services mechanism feature.
      */
-    public void setServicesMechnism(boolean flag) {
-        _useServicesMechanism = flag;
+    public void setOverrideDefaultParser(boolean flag) {
+        _overrideDefaultParser = flag;
     }
 
   // -------------------- private methods --------------------
--- a/src/java.xml/share/classes/com/sun/org/apache/xml/internal/dtm/ref/DTMManagerDefault.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.xml/share/classes/com/sun/org/apache/xml/internal/dtm/ref/DTMManagerDefault.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2017, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * Licensed to the Apache Software Foundation (ASF) under one or more
@@ -20,7 +20,6 @@
 
 package com.sun.org.apache.xml.internal.dtm.ref;
 
-import com.sun.org.apache.xalan.internal.utils.FactoryImpl;
 import javax.xml.parsers.DocumentBuilder;
 import javax.xml.parsers.DocumentBuilderFactory;
 import javax.xml.transform.Source;
@@ -43,6 +42,7 @@
 import com.sun.org.apache.xml.internal.utils.SystemIDResolver;
 import com.sun.org.apache.xml.internal.utils.XMLReaderManager;
 import com.sun.org.apache.xml.internal.utils.XMLStringFactory;
+import jdk.xml.internal.JdkXmlUtils;
 
 import org.w3c.dom.Document;
 import org.w3c.dom.Node;
@@ -606,7 +606,7 @@
       // If user did not supply a reader, ask for one from the reader manager
       if (null == reader) {
         if (m_readerManager == null) {
-            m_readerManager = XMLReaderManager.getInstance(super.useServicesMechnism());
+            m_readerManager = XMLReaderManager.getInstance(super.overrideDefaultParser());
         }
 
         reader = m_readerManager.getXMLReader();
@@ -765,8 +765,7 @@
 
     try
     {
-      DocumentBuilderFactory dbf = FactoryImpl.getDOMFactory(super.useServicesMechnism());
-      dbf.setNamespaceAware(true);
+      DocumentBuilderFactory dbf = JdkXmlUtils.getDOMFactory(super.overrideDefaultParser());
 
       DocumentBuilder db = dbf.newDocumentBuilder();
       Document doc = db.newDocument();
--- a/src/java.xml/share/classes/com/sun/org/apache/xml/internal/utils/AttList.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.xml/share/classes/com/sun/org/apache/xml/internal/utils/AttList.java	Fri Jan 19 09:32:10 2018 -0800
@@ -45,9 +45,7 @@
   /**
    * Constructor AttList
    *
-   *
    * @param attrs List of attributes this will contain
-   * @param dh DOMHelper
    */
   public AttList(NamedNodeMap attrs)
   {
--- a/src/java.xml/share/classes/com/sun/org/apache/xml/internal/utils/XMLReaderManager.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.xml/share/classes/com/sun/org/apache/xml/internal/utils/XMLReaderManager.java	Fri Jan 19 09:32:10 2018 -0800
@@ -21,14 +21,10 @@
 package com.sun.org.apache.xml.internal.utils;
 
 import com.sun.org.apache.xalan.internal.XalanConstants;
-import com.sun.org.apache.xalan.internal.utils.FactoryImpl;
 import com.sun.org.apache.xalan.internal.utils.XMLSecurityManager;
 import java.util.HashMap;
 import javax.xml.XMLConstants;
 import javax.xml.catalog.CatalogFeatures;
-import javax.xml.parsers.FactoryConfigurationError;
-import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.parsers.SAXParserFactory;
 import jdk.xml.internal.JdkXmlFeatures;
 import jdk.xml.internal.JdkXmlUtils;
 import jdk.xml.internal.SecuritySupport;
@@ -36,7 +32,6 @@
 import org.xml.sax.SAXNotRecognizedException;
 import org.xml.sax.SAXNotSupportedException;
 import org.xml.sax.XMLReader;
-import org.xml.sax.helpers.XMLReaderFactory;
 
 /**
  * Creates XMLReader objects and caches them for re-use.
@@ -44,32 +39,23 @@
  *
  * @LastModified: Sep 2017
  */
-@SuppressWarnings("deprecation") //org.xml.sax.helpers.XMLReaderFactory
 public class XMLReaderManager {
 
-    private static final String NAMESPACES_FEATURE =
-                             "http://xml.org/sax/features/namespaces";
-    private static final String NAMESPACE_PREFIXES_FEATURE =
-                             "http://xml.org/sax/features/namespace-prefixes";
     private static final XMLReaderManager m_singletonManager =
                                                      new XMLReaderManager();
     private static final String property = "org.xml.sax.driver";
-    /**
-     * Parser factory to be used to construct XMLReader objects
-     */
-    private static SAXParserFactory m_parserFactory;
 
     /**
      * Cache of XMLReader objects
      */
-    private ThreadLocal<XMLReader> m_readers;
+    private ThreadLocal<ReaderWrapper> m_readers;
 
     /**
      * Keeps track of whether an XMLReader object is in use.
      */
     private HashMap<XMLReader, Boolean> m_inUse;
 
-    private boolean m_useServicesMechanism = true;
+    private boolean m_overrideDefaultParser;
 
     private boolean _secureProcessing;
      /**
@@ -94,8 +80,8 @@
     /**
      * Retrieves the singleton reader manager
      */
-    public static XMLReaderManager getInstance(boolean useServicesMechanism) {
-        m_singletonManager.setServicesMechnism(useServicesMechanism);
+    public static XMLReaderManager getInstance(boolean overrideDefaultParser) {
+        m_singletonManager.setOverrideDefaultParser(overrideDefaultParser);
         return m_singletonManager;
     }
 
@@ -118,61 +104,30 @@
             m_inUse = new HashMap<>();
         }
 
-        // If the cached reader for this thread is in use, construct a new
-        // one; otherwise, return the cached reader unless it isn't an
-        // instance of the class set in the 'org.xml.sax.driver' property
-        reader = m_readers.get();
-        boolean threadHasReader = (reader != null);
+        /**
+         * Constructs a new XMLReader if:
+         * (1) the cached reader for this thread is in use, or
+         * (2) the requirement for overriding has changed,
+         * (3) the cached reader isn't an instance of the class set in the
+         * 'org.xml.sax.driver' property
+         *
+         * otherwise, returns the cached reader
+         */
+        ReaderWrapper rw = m_readers.get();
+        boolean threadHasReader = (rw != null);
+        reader = threadHasReader ? rw.reader : null;
         String factory = SecuritySupport.getSystemProperty(property);
         if (threadHasReader && m_inUse.get(reader) != Boolean.TRUE &&
+                (rw.overrideDefaultParser == m_overrideDefaultParser) &&
                 ( factory == null || reader.getClass().getName().equals(factory))) {
             m_inUse.put(reader, Boolean.TRUE);
         } else {
-            try {
-                try {
-                    // According to JAXP 1.2 specification, if a SAXSource
-                    // is created using a SAX InputSource the Transformer or
-                    // TransformerFactory creates a reader via the
-                    // XMLReaderFactory if setXMLReader is not used
-                    reader = XMLReaderFactory.createXMLReader();
-                    try {
-                        reader.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, _secureProcessing);
-                    } catch (SAXNotRecognizedException e) {
-                        XMLSecurityManager.printWarning(reader.getClass().getName(),
-                                XMLConstants.FEATURE_SECURE_PROCESSING, e);
-                    }
-                } catch (SAXException e) {
-                   try {
-                        // If unable to create an instance, let's try to use
-                        // the XMLReader from JAXP
-                        if (m_parserFactory == null) {
-                            m_parserFactory = FactoryImpl.getSAXFactory(m_useServicesMechanism);
-                            m_parserFactory.setNamespaceAware(true);
-                        }
-
-                        reader = m_parserFactory.newSAXParser().getXMLReader();
-                   } catch (ParserConfigurationException pce) {
-                       throw pce;   // pass along pce
-                   }
-                }
-                try {
-                    reader.setFeature(NAMESPACES_FEATURE, true);
-                    reader.setFeature(NAMESPACE_PREFIXES_FEATURE, false);
-                } catch (SAXException se) {
-                    // Try to carry on if we've got a parser that
-                    // doesn't know about namespace prefixes.
-                }
-            } catch (ParserConfigurationException ex) {
-                throw new SAXException(ex);
-            } catch (FactoryConfigurationError ex1) {
-                throw new SAXException(ex1.toString());
-            } catch (NoSuchMethodError | AbstractMethodError ex2) {
-            }
+            reader = JdkXmlUtils.getXMLReader(m_overrideDefaultParser, _secureProcessing);
 
             // Cache the XMLReader if this is the first time we've created
             // a reader for this thread.
             if (!threadHasReader) {
-                m_readers.set(reader);
+                m_readers.set(new ReaderWrapper(reader, m_overrideDefaultParser));
                 m_inUse.put(reader, Boolean.TRUE);
             }
         }
@@ -230,22 +185,23 @@
     public synchronized void releaseXMLReader(XMLReader reader) {
         // If the reader that's being released is the cached reader
         // for this thread, remove it from the m_isUse list.
-        if (m_readers.get() == reader && reader != null) {
+        ReaderWrapper rw = m_readers.get();
+        if (rw.reader == reader && reader != null) {
             m_inUse.remove(reader);
         }
     }
     /**
      * Return the state of the services mechanism feature.
      */
-    public boolean useServicesMechnism() {
-        return m_useServicesMechanism;
+    public boolean overrideDefaultParser() {
+        return m_overrideDefaultParser;
     }
 
     /**
      * Set the state of the services mechanism feature.
      */
-    public void setServicesMechnism(boolean flag) {
-        m_useServicesMechanism = flag;
+    public void setOverrideDefaultParser(boolean flag) {
+        m_overrideDefaultParser = flag;
     }
 
     /**
@@ -285,4 +241,14 @@
             _cdataChunkSize = JdkXmlUtils.getValue(value, _cdataChunkSize);
         }
     }
+
+    class ReaderWrapper {
+        XMLReader reader;
+        boolean overrideDefaultParser;
+
+        public ReaderWrapper(XMLReader reader, boolean overrideDefaultParser) {
+            this.reader = reader;
+            this.overrideDefaultParser = overrideDefaultParser;
+        }
+    }
 }
--- a/src/java.xml/share/classes/com/sun/org/apache/xpath/internal/CachedXPathAPI.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.xml/share/classes/com/sun/org/apache/xpath/internal/CachedXPathAPI.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,6 +1,5 @@
 /*
- * reserved comment block
- * DO NOT REMOVE OR ALTER!
+ * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * Licensed to the Apache Software Foundation (ASF) under one or more
@@ -26,6 +25,7 @@
 import com.sun.org.apache.xml.internal.utils.PrefixResolver;
 import com.sun.org.apache.xml.internal.utils.PrefixResolverDefault;
 import com.sun.org.apache.xpath.internal.objects.XObject;
+import jdk.xml.internal.JdkXmlUtils;
 
 import org.w3c.dom.Document;
 import org.w3c.dom.Node;
@@ -73,7 +73,7 @@
    */
   public CachedXPathAPI()
   {
-    xpathSupport = new XPathContext();
+    xpathSupport = new XPathContext(JdkXmlUtils.OVERRIDE_PARSER_DEFAULT);
   }
 
   /**
@@ -328,7 +328,7 @@
     XPath xpath = new XPath(str, null, prefixResolver, XPath.SELECT, null);
 
     // Execute the XPath, and have it return the result
-    XPathContext xpathSupport = new XPathContext();
+    XPathContext xpathSupport = new XPathContext(JdkXmlUtils.OVERRIDE_PARSER_DEFAULT);
     int ctxtNode = xpathSupport.getDTMHandleFromNode(contextNode);
 
     return xpath.execute(xpathSupport, ctxtNode, prefixResolver);
--- a/src/java.xml/share/classes/com/sun/org/apache/xpath/internal/XPathAPI.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.xml/share/classes/com/sun/org/apache/xpath/internal/XPathAPI.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,6 +1,5 @@
 /*
- * reserved comment block
- * DO NOT REMOVE OR ALTER!
+ * Copyright (c) 2011, 2017, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * Licensed to the Apache Software Foundation (ASF) under one or more
@@ -26,6 +25,7 @@
 import com.sun.org.apache.xml.internal.utils.PrefixResolver;
 import com.sun.org.apache.xml.internal.utils.PrefixResolverDefault;
 import com.sun.org.apache.xpath.internal.objects.XObject;
+import jdk.xml.internal.JdkXmlUtils;
 
 import org.w3c.dom.Document;
 import org.w3c.dom.Node;
@@ -221,7 +221,7 @@
     // (Changed from: XPathContext xpathSupport = new XPathContext();
     //    because XPathContext is weak in a number of areas... perhaps
     //    XPathContext should be done away with.)
-    XPathContext xpathSupport = new XPathContext();
+    XPathContext xpathSupport = new XPathContext(JdkXmlUtils.OVERRIDE_PARSER_DEFAULT);
 
     // Create an object to resolve namespace prefixes.
     // XPath namespaces are resolved from the input context node's document element
@@ -276,7 +276,7 @@
     XPath xpath = new XPath(str, null, prefixResolver, XPath.SELECT, null);
 
     // Execute the XPath, and have it return the result
-    XPathContext xpathSupport = new XPathContext();
+    XPathContext xpathSupport = new XPathContext(JdkXmlUtils.OVERRIDE_PARSER_DEFAULT);
     int ctxtNode = xpathSupport.getDTMHandleFromNode(contextNode);
 
     return xpath.execute(xpathSupport, ctxtNode, prefixResolver);
--- a/src/java.xml/share/classes/com/sun/org/apache/xpath/internal/XPathContext.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.xml/share/classes/com/sun/org/apache/xpath/internal/XPathContext.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,6 @@
 /*
- * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2017, Oracle and/or its affiliates. All rights reserved.
+ * @LastModified: Oct 2017
  */
 /*
  * Licensed to the Apache Software Foundation (ASF) under one or more
@@ -49,6 +50,7 @@
 import javax.xml.transform.ErrorListener;
 import javax.xml.transform.SourceLocator;
 import javax.xml.transform.URIResolver;
+import jdk.xml.internal.JdkXmlUtils;
 import org.xml.sax.XMLReader;
 
 /**
@@ -92,7 +94,7 @@
    */
   private boolean m_isSecureProcessing = false;
 
-  private boolean m_useServicesMechanism = true;
+  private boolean m_overrideDefaultParser;
 
   /**
    * Though XPathContext context extends
@@ -305,11 +307,11 @@
    */
   public XPathContext()
   {
-    this(true);
+    this(false);
   }
 
-  public XPathContext(boolean useServicesMechanism) {
-      init(useServicesMechanism);
+  public XPathContext(boolean overrideDefaultParser) {
+      init(overrideDefaultParser);
   }
   /**
    **This constructor doesn't seem to be used anywhere -- huizhe wang**
@@ -324,15 +326,15 @@
       m_ownerGetErrorListener = m_owner.getClass().getMethod("getErrorListener", new Class<?>[] {});
     }
     catch (NoSuchMethodException nsme) {}
-    init(true);
+    init(false);
   }
 
-  private void init(boolean useServicesMechanism) {
+  private void init(boolean overrideDefaultParser) {
     m_prefixResolvers.push(null);
     m_currentNodes.push(DTM.NULL);
     m_currentExpressionNodes.push(DTM.NULL);
     m_saxLocations.push(null);
-    m_useServicesMechanism = useServicesMechanism;
+    m_overrideDefaultParser = overrideDefaultParser;
     m_dtmManager = DTMManager.newInstance(
                    com.sun.org.apache.xpath.internal.objects.XMLStringFactoryImpl.getFactory()
                    );
@@ -1082,15 +1084,15 @@
     /**
      * Return the state of the services mechanism feature.
      */
-    public boolean useServicesMechnism() {
-        return m_useServicesMechanism;
+    public boolean overrideDefaultParser() {
+        return m_overrideDefaultParser;
     }
 
     /**
      * Set the state of the services mechanism feature.
      */
-    public void setServicesMechnism(boolean flag) {
-        m_useServicesMechanism = flag;
+    public void setOverrideDefaultParser(boolean flag) {
+        m_overrideDefaultParser = flag;
     }
 
     /**
--- a/src/java.xml/share/classes/com/sun/org/apache/xpath/internal/jaxp/XPathExpressionImpl.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.xml/share/classes/com/sun/org/apache/xpath/internal/jaxp/XPathExpressionImpl.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2017, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * Licensed to the Apache Software Foundation (ASF) under one or more
@@ -31,7 +31,6 @@
 import javax.xml.xpath.XPathVariableResolver;
 import jdk.xml.internal.JdkXmlFeatures;
 import org.w3c.dom.Document;
-import org.w3c.dom.Node;
 import org.xml.sax.InputSource;
 
 /**
@@ -47,8 +46,7 @@
      * from the context.
      */
     protected XPathExpressionImpl() {
-        this(null, null, null, null,
-             false, true, new JdkXmlFeatures(false));
+        this(null, null, null, null, false, new JdkXmlFeatures(false));
     };
 
     protected XPathExpressionImpl(com.sun.org.apache.xpath.internal.XPath xpath,
@@ -56,19 +54,20 @@
             XPathFunctionResolver functionResolver,
             XPathVariableResolver variableResolver) {
         this(xpath, prefixResolver, functionResolver, variableResolver,
-             false, true, new JdkXmlFeatures(false));
+             false, new JdkXmlFeatures(false));
     };
 
     protected XPathExpressionImpl(com.sun.org.apache.xpath.internal.XPath xpath,
             JAXPPrefixResolver prefixResolver,XPathFunctionResolver functionResolver,
             XPathVariableResolver variableResolver, boolean featureSecureProcessing,
-            boolean useServiceMechanism, JdkXmlFeatures featureManager) {
+            JdkXmlFeatures featureManager) {
         this.xpath = xpath;
         this.prefixResolver = prefixResolver;
         this.functionResolver = functionResolver;
         this.variableResolver = variableResolver;
         this.featureSecureProcessing = featureSecureProcessing;
-        this.useServiceMechanism = useServiceMechanism;
+        this.overrideDefaultParser = featureManager.getFeature(
+                JdkXmlFeatures.XmlFeature.JDK_OVERRIDE_PARSER);
         this.featureManager = featureManager;
     };
 
--- a/src/java.xml/share/classes/com/sun/org/apache/xpath/internal/jaxp/XPathFactoryImpl.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.xml/share/classes/com/sun/org/apache/xpath/internal/jaxp/XPathFactoryImpl.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2017, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * Licensed to the Apache Software Foundation (ASF) under one or more
@@ -60,29 +60,21 @@
          * <p>State of secure mode.</p>
          */
         private boolean _isSecureMode = false;
+
+        /**
+         * XML Features manager
+         */
+        private final JdkXmlFeatures _featureManager;
+
         /**
          * javax.xml.xpath.XPathFactory implementation.
          */
-
-        private boolean _useServicesMechanism = true;
-
-        private final JdkXmlFeatures _featureManager;
-
         public XPathFactoryImpl() {
-            this(true);
-        }
-
-        public static XPathFactory newXPathFactoryNoServiceLoader() {
-            return new XPathFactoryImpl(false);
-        }
-
-        public XPathFactoryImpl(boolean useServicesMechanism) {
             if (System.getSecurityManager() != null) {
                 _isSecureMode = true;
                 _isNotSecureProcessing = false;
             }
             _featureManager = new JdkXmlFeatures(!_isNotSecureProcessing);
-            this._useServicesMechanism = useServicesMechanism;
         }
         /**
          * <p>Is specified object model supported by this
@@ -132,8 +124,7 @@
         public javax.xml.xpath.XPath newXPath() {
             return new com.sun.org.apache.xpath.internal.jaxp.XPathImpl(
                     xPathVariableResolver, xPathFunctionResolver,
-                    !_isNotSecureProcessing, _useServicesMechanism,
-                    _featureManager );
+                    !_isNotSecureProcessing, _featureManager );
         }
 
         /**
@@ -192,10 +183,9 @@
                 return;
             }
             if (name.equals(XalanConstants.ORACLE_FEATURE_SERVICE_MECHANISM)) {
-                //in secure mode, let _useServicesMechanism be determined by the constructor
-                if (!_isSecureMode)
-                    _useServicesMechanism = value;
-                return;
+                // for compatibility, in secure mode, useServicesMechanism is determined by the constructor
+                if (_isSecureMode)
+                    return;
             }
 
             if (_featureManager != null &&
@@ -248,9 +238,6 @@
             if (name.equals(XMLConstants.FEATURE_SECURE_PROCESSING)) {
                 return !_isNotSecureProcessing;
             }
-            if (name.equals(XalanConstants.ORACLE_FEATURE_SERVICE_MECHANISM)) {
-                return _useServicesMechanism;
-            }
 
             /** Check to see if the property is managed by the feature manager **/
             int index = _featureManager.getIndex(name);
--- a/src/java.xml/share/classes/com/sun/org/apache/xpath/internal/jaxp/XPathImpl.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.xml/share/classes/com/sun/org/apache/xpath/internal/jaxp/XPathImpl.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2017, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * Licensed to the Apache Software Foundation (ASF) under one or more
@@ -54,17 +54,18 @@
     private NamespaceContext namespaceContext=null;
 
     XPathImpl(XPathVariableResolver vr, XPathFunctionResolver fr) {
-        this(vr, fr, false, true, new JdkXmlFeatures(false));
+        this(vr, fr, false, new JdkXmlFeatures(false));
     }
 
     XPathImpl(XPathVariableResolver vr, XPathFunctionResolver fr,
-            boolean featureSecureProcessing, boolean useServiceMechanism,
-            JdkXmlFeatures featureManager) {
+            boolean featureSecureProcessing, JdkXmlFeatures featureManager) {
         this.origVariableResolver = this.variableResolver = vr;
         this.origFunctionResolver = this.functionResolver = fr;
         this.featureSecureProcessing = featureSecureProcessing;
-        this.useServiceMechanism = useServiceMechanism;
         this.featureManager = featureManager;
+        overrideDefaultParser = featureManager.getFeature(
+                JdkXmlFeatures.XmlFeature.JDK_OVERRIDE_PARSER);
+
     }
 
 
@@ -163,7 +164,7 @@
             // Can have errorListener
             XPathExpressionImpl ximpl = new XPathExpressionImpl (xpath,
                     prefixResolver, functionResolver, variableResolver,
-                    featureSecureProcessing, useServiceMechanism, featureManager);
+                    featureSecureProcessing, featureManager);
             return ximpl;
         } catch (TransformerException te) {
             throw new XPathExpressionException (te) ;
--- a/src/java.xml/share/classes/com/sun/org/apache/xpath/internal/jaxp/XPathImplUtil.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.xml/share/classes/com/sun/org/apache/xpath/internal/jaxp/XPathImplUtil.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2017, 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
@@ -26,7 +26,6 @@
 package com.sun.org.apache.xpath.internal.jaxp;
 
 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;
@@ -43,6 +42,7 @@
 import javax.xml.xpath.XPathNodes;
 import javax.xml.xpath.XPathVariableResolver;
 import jdk.xml.internal.JdkXmlFeatures;
+import jdk.xml.internal.JdkXmlUtils;
 import org.w3c.dom.Document;
 import org.w3c.dom.Node;
 import org.w3c.dom.traversal.NodeIterator;
@@ -57,7 +57,7 @@
     XPathFunctionResolver functionResolver;
     XPathVariableResolver variableResolver;
     JAXPPrefixResolver prefixResolver;
-    boolean useServiceMechanism = true;
+    boolean overrideDefaultParser;
     // By default Extension Functions are allowed in XPath Expressions. If
     // Secure Processing Feature is set on XPathFactory then the invocation of
     // extensions function need to throw XPathFunctionException
@@ -125,9 +125,7 @@
             //
             // so we really have to create a fresh DocumentBuilder every time we need one
             // - KK
-            DocumentBuilderFactory dbf = FactoryImpl.getDOMFactory(useServiceMechanism);
-            dbf.setNamespaceAware(true);
-            dbf.setValidating(false);
+            DocumentBuilderFactory dbf = JdkXmlUtils.getDOMFactory(overrideDefaultParser);
             return dbf.newDocumentBuilder().parse(source);
         } catch (ParserConfigurationException | SAXException | IOException e) {
             throw new XPathExpressionException (e);
--- a/src/java.xml/share/classes/javax/xml/catalog/CatalogMessages.properties	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.xml/share/classes/javax/xml/catalog/CatalogMessages.properties	Fri Jan 19 09:32:10 2018 -0800
@@ -30,6 +30,7 @@
 CircularReference = JAXP09010001: Circular reference is not allowed: ''{0}''.
 
 # Input or configuration errors
+# Technical term, do not translate: catalog
 InvalidCatalog = JAXP09020001: The document element of a catalog must be catalog.
 InvalidEntryType = JAXP09020002: The entry type ''{0}'' is not valid.
 UriNotAbsolute = JAXP09020003: The specified URI ''{0}'' is not absolute.
@@ -41,12 +42,16 @@
 
 # Parsing errors
 ParserConf = JAXP09030001: Unexpected error while configuring a SAX parser.
+# Technical term, do not translate: catalog
 ParsingFailed = JAXP09030002: Failed to parse the catalog file.
+# Technical term, do not translate: catalog
 NoCatalogFound = JAXP09030003: No Catalog is specified.
 
 
 # Resolving errors
 NoMatchFound = JAXP09040001: No match found for publicId ''{0}'' and systemId ''{1}''.
+# Technical term, do not translate: href, base
 NoMatchURIFound = JAXP09040002: No match found for href ''{0}'' and base ''{1}''.
+# Technical term, do not translate: href, base
 FailedCreatingURI = JAXP09040003: Can not construct URI using href ''{0}'' and base ''{1}''.
 
--- a/src/java.xml/share/classes/javax/xml/transform/FactoryFinder.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.xml/share/classes/javax/xml/transform/FactoryFinder.java	Fri Jan 19 09:32:10 2018 -0800
@@ -143,10 +143,11 @@
      * @param doFallback True if the current ClassLoader should be tried as
      * a fallback if the class is not found using cl
      *
-     * @param useServicesMechanism True use services mechanism
+     * @param overrideDefaultParser True to allow overriding the system-default
+     * parser.
      */
     static <T> T newInstance(Class<T> type, String className, ClassLoader cl,
-                             boolean doFallback, boolean useServicesMechanism)
+                             boolean doFallback)
         throws TransformerFactoryConfigurationError
     {
         assert type != null;
@@ -165,13 +166,8 @@
             if (!type.isAssignableFrom(providerClass)) {
                 throw new ClassCastException(className + " cannot be cast to " + type.getName());
             }
-            Object instance = null;
-            if (!useServicesMechanism) {
-                instance = newInstanceNoServiceLoader(type, providerClass);
-            }
-            if (instance == null) {
-                instance = providerClass.getConstructor().newInstance();
-            }
+            Object instance = providerClass.getConstructor().newInstance();
+
             final ClassLoader clD = cl;
             dPrint(()->"created new instance of " + providerClass +
                        " using ClassLoader: " + clD);
@@ -188,48 +184,6 @@
     }
 
     /**
-     * Try to construct using newTransformerFactoryNoServiceLoader
-     *   method if available.
-     */
-    private static <T> T newInstanceNoServiceLoader(Class<T> type, Class<?> providerClass) {
-        // Retain maximum compatibility if no security manager.
-        if (System.getSecurityManager() == null) {
-            return null;
-        }
-        try {
-            final Method creationMethod =
-                    providerClass.getDeclaredMethod(
-                        "newTransformerFactoryNoServiceLoader"
-                    );
-            final int modifiers = creationMethod.getModifiers();
-
-            // Do not call the method if it's not public static.
-            if (!Modifier.isPublic(modifiers) || !Modifier.isStatic(modifiers)) {
-                return null;
-            }
-
-            // Only call the method if it's declared to return an instance of
-            // TransformerFactory
-            final Class<?> returnType = creationMethod.getReturnType();
-            if (type.isAssignableFrom(returnType)) {
-                final Object result = creationMethod.invoke(null, (Object[])null);
-                return type.cast(result);
-            } else {
-                // This should not happen, as
-                // TransformerFactoryImpl.newTransformerFactoryNoServiceLoader is
-                // declared to return TransformerFactory.
-                throw new ClassCastException(returnType + " cannot be cast to " + type);
-            }
-        } catch (ClassCastException e) {
-            throw new TransformerFactoryConfigurationError(e, e.getMessage());
-        } catch (NoSuchMethodException exc) {
-            return null;
-        } catch (Exception exc) {
-            return null;
-        }
-    }
-
-    /**
      * Finds the implementation Class object in the specified order.  Main
      * entry point.
      * @return Class object of factory, never null
@@ -255,7 +209,7 @@
             String systemProp = SecuritySupport.getSystemProperty(factoryId);
             if (systemProp != null) {
                 dPrint(()->"found system property, value=" + systemProp);
-                return newInstance(type, systemProp, null, true, true);
+                return newInstance(type, systemProp, null, true);
             }
         }
         catch (SecurityException se) {
@@ -282,7 +236,7 @@
 
             if (factoryClassName != null) {
                 dPrint(()->"found in ${java.home}/conf/jaxp.properties, value=" + factoryClassName);
-                return newInstance(type, factoryClassName, null, true, true);
+                return newInstance(type, factoryClassName, null, true);
             }
         }
         catch (Exception ex) {
@@ -300,7 +254,7 @@
         }
 
         dPrint(()->"loaded from fallback value: " + fallbackClassName);
-        return newInstance(type, fallbackClassName, null, true, true);
+        return newInstance(type, fallbackClassName, null, true);
     }
 
     /*
--- a/src/java.xml/share/classes/javax/xml/transform/TransformerFactory.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.xml/share/classes/javax/xml/transform/TransformerFactory.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2017, 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
@@ -62,7 +62,7 @@
      * @since 9
      */
     public static TransformerFactory newDefaultInstance() {
-        return TransformerFactoryImpl.newTransformerFactoryNoServiceLoader();
+        return new TransformerFactoryImpl();
     }
 
     /**
@@ -170,7 +170,7 @@
 
         //do not fallback if given classloader can't find the class, throw exception
         return  FactoryFinder.newInstance(TransformerFactory.class,
-                    factoryClassName, classLoader, false, false);
+                    factoryClassName, classLoader, false);
     }
     /**
      * Process the {@code Source} into a {@code Transformer}
--- a/src/java.xml/share/classes/javax/xml/validation/SchemaFactory.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.xml/share/classes/javax/xml/validation/SchemaFactory.java	Fri Jan 19 09:32:10 2018 -0800
@@ -139,7 +139,7 @@
      * @since 9
      */
     public static SchemaFactory newDefaultInstance() {
-        return XMLSchemaFactory.newXMLSchemaFactoryNoServiceLoader();
+        return new XMLSchemaFactory();
     }
 
     /**
--- a/src/java.xml/share/classes/javax/xml/validation/SchemaFactoryFinder.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.xml/share/classes/javax/xml/validation/SchemaFactoryFinder.java	Fri Jan 19 09:32:10 2018 -0800
@@ -25,6 +25,7 @@
 
 package javax.xml.validation;
 
+import com.sun.org.apache.xerces.internal.jaxp.validation.XMLSchemaFactory;
 import java.io.File;
 import java.lang.reflect.InvocationTargetException;
 import java.lang.reflect.Method;
@@ -167,7 +168,7 @@
             String r = SecuritySupport.getSystemProperty(propertyName);
             if(r!=null) {
                 debugPrintln(()->"The value is '"+r+"'");
-                sf = createInstance(r, true);
+                sf = createInstance(r);
                 if(sf!=null)    return sf;
             } else
                 debugPrintln(()->"The property is undefined.");
@@ -201,7 +202,7 @@
             debugPrintln(()->"found " + factoryClassName + " in $java.home/conf/jaxp.properties");
 
             if (factoryClassName != null) {
-                sf = createInstance(factoryClassName, true);
+                sf = createInstance(factoryClassName);
                 if(sf != null){
                     return sf;
                 }
@@ -226,7 +227,7 @@
         // platform default
         if(schemaLanguage.equals("http://www.w3.org/2001/XMLSchema")) {
             debugPrintln(()->"attempting to use the platform default XML Schema validator");
-            return createInstance("com.sun.org.apache.xerces.internal.jaxp.validation.XMLSchemaFactory", true);
+            return new XMLSchemaFactory();
         }
 
         debugPrintln(()->"all things were tried, but none was found. bailing out.");
@@ -273,11 +274,7 @@
      * @return null
      *      if it fails. Error messages will be printed by this method.
      */
-    SchemaFactory createInstance( String className ) {
-        return createInstance( className, false );
-    }
-
-    SchemaFactory createInstance( String className, boolean useServicesMechanism ) {
+    SchemaFactory createInstance(String className) {
         SchemaFactory schemaFactory = null;
 
         debugPrintln(()->"createInstance(" + className + ")");
@@ -296,12 +293,7 @@
                 throw new ClassCastException(clazz.getName()
                             + " cannot be cast to " + SchemaFactory.class);
             }
-            if (!useServicesMechanism) {
-                schemaFactory = newInstanceNoServiceLoader(clazz);
-            }
-            if (schemaFactory == null) {
-                schemaFactory = (SchemaFactory) clazz.getConstructor().newInstance();
-            }
+            schemaFactory = (SchemaFactory) clazz.getConstructor().newInstance();
         } catch (ClassCastException | IllegalAccessException | IllegalArgumentException |
             InstantiationException | InvocationTargetException | NoSuchMethodException |
             SecurityException ex) {
@@ -315,50 +307,6 @@
         return schemaFactory;
     }
 
-    /**
-     * Try to construct using newXMLSchemaFactoryNoServiceLoader
-     *   method if available.
-     */
-    private static SchemaFactory newInstanceNoServiceLoader(
-         Class<?> providerClass
-    ) {
-        // Retain maximum compatibility if no security manager.
-        if (System.getSecurityManager() == null) {
-            return null;
-        }
-        try {
-            final Method creationMethod =
-                providerClass.getDeclaredMethod(
-                    "newXMLSchemaFactoryNoServiceLoader"
-                );
-            final int modifiers = creationMethod.getModifiers();
-
-            // Do not call the method if it's not public static.
-            if (!Modifier.isStatic(modifiers) || !Modifier.isPublic(modifiers)) {
-                return null;
-            }
-
-            // Only calls "newXMLSchemaFactoryNoServiceLoader" if it's
-            // declared to return an instance of SchemaFactory.
-            final Class<?> returnType = creationMethod.getReturnType();
-            if (SERVICE_CLASS.isAssignableFrom(returnType)) {
-                return SERVICE_CLASS.cast(creationMethod.invoke(null, (Object[])null));
-            } else {
-                // Should not happen since
-                // XMLSchemaFactory.newXMLSchemaFactoryNoServiceLoader is
-                // declared to return XMLSchemaFactory.
-                throw new ClassCastException(returnType
-                            + " cannot be cast to " + SERVICE_CLASS);
-            }
-        } catch(ClassCastException e) {
-            throw new SchemaFactoryConfigurationError(e.getMessage(), e);
-        } catch (NoSuchMethodException exc) {
-            return null;
-        } catch (Exception exc) {
-            return null;
-        }
-    }
-
     // Call isSchemaLanguageSupported with initial context.
     private boolean isSchemaLanguageSupportedBy(final SchemaFactory factory,
             final String schemaLanguage,
--- a/src/java.xml/share/classes/javax/xml/xpath/XPathFactory.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.xml/share/classes/javax/xml/xpath/XPathFactory.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2017, 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
@@ -87,7 +87,7 @@
      * @since 9
      */
     public static XPathFactory newDefaultInstance() {
-        return XPathFactoryImpl.newXPathFactoryNoServiceLoader();
+        return new XPathFactoryImpl();
     }
 
     /**
--- a/src/java.xml/share/classes/javax/xml/xpath/XPathFactoryFinder.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.xml/share/classes/javax/xml/xpath/XPathFactoryFinder.java	Fri Jan 19 09:32:10 2018 -0800
@@ -25,10 +25,9 @@
 
 package javax.xml.xpath;
 
+import com.sun.org.apache.xpath.internal.jaxp.XPathFactoryImpl;
 import java.io.File;
 import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.lang.reflect.Modifier;
 import java.security.AccessControlContext;
 import java.security.AccessController;
 import java.security.PrivilegedAction;
@@ -162,7 +161,7 @@
             String r = SecuritySupport.getSystemProperty(propertyName);
             if(r!=null) {
                 debugPrintln(()->"The value is '"+r+"'");
-                xpathFactory = createInstance(r, true);
+                xpathFactory = createInstance(r);
                 if (xpathFactory != null) {
                     return xpathFactory;
                 }
@@ -197,7 +196,7 @@
             debugPrintln(()->"found " + factoryClassName + " in $java.home/conf/jaxp.properties");
 
             if (factoryClassName != null) {
-                xpathFactory = createInstance(factoryClassName, true);
+                xpathFactory = createInstance(factoryClassName);
                 if(xpathFactory != null){
                     return xpathFactory;
                 }
@@ -223,7 +222,7 @@
         // platform default
         if(uri.equals(XPathFactory.DEFAULT_OBJECT_MODEL_URI)) {
             debugPrintln(()->"attempting to use the platform default W3C DOM XPath lib");
-            return createInstance("com.sun.org.apache.xpath.internal.jaxp.XPathFactoryImpl", true);
+            return new XPathFactoryImpl();
         }
 
         debugPrintln(()->"all things were tried, but none was found. bailing out.");
@@ -271,13 +270,7 @@
      * @return null
      *      if it fails. Error messages will be printed by this method.
      */
-    XPathFactory createInstance( String className )
-            throws XPathFactoryConfigurationException
-    {
-        return createInstance( className, false );
-    }
-
-    XPathFactory createInstance( String className, boolean useServicesMechanism  )
+    XPathFactory createInstance(String className)
             throws XPathFactoryConfigurationException
     {
         XPathFactory xPathFactory = null;
@@ -294,12 +287,7 @@
 
         // instantiate Class as a XPathFactory
         try {
-            if (!useServicesMechanism) {
-                xPathFactory = newInstanceNoServiceLoader(clazz);
-            }
-            if (xPathFactory == null) {
-                xPathFactory = (XPathFactory) clazz.getConstructor().newInstance();
-            }
+            xPathFactory = (XPathFactory) clazz.getConstructor().newInstance();
         } catch (ClassCastException | IllegalAccessException | IllegalArgumentException |
             InstantiationException | InvocationTargetException | NoSuchMethodException |
             SecurityException ex) {
@@ -312,50 +300,6 @@
 
         return xPathFactory;
     }
-    /**
-     * Try to construct using newXPathFactoryNoServiceLoader
-     *   method if available.
-     */
-    private static XPathFactory newInstanceNoServiceLoader(
-         Class<?> providerClass
-    ) throws XPathFactoryConfigurationException {
-        // Retain maximum compatibility if no security manager.
-        if (System.getSecurityManager() == null) {
-            return null;
-        }
-        try {
-            Method creationMethod =
-                    providerClass.getDeclaredMethod(
-                        "newXPathFactoryNoServiceLoader"
-                    );
-            final int modifiers = creationMethod.getModifiers();
-
-            // Do not call "newXPathFactoryNoServiceLoader" if it's
-            // not public static.
-            if (!Modifier.isStatic(modifiers) || !Modifier.isPublic(modifiers)) {
-                return null;
-            }
-
-            // Only calls "newXPathFactoryNoServiceLoader" if it's
-            // declared to return an instance of XPathFactory.
-            final Class<?> returnType = creationMethod.getReturnType();
-            if (SERVICE_CLASS.isAssignableFrom(returnType)) {
-                return SERVICE_CLASS.cast(creationMethod.invoke(null, (Object[])null));
-            } else {
-                // Should not happen since
-                // XPathFactoryImpl.newXPathFactoryNoServiceLoader is
-                // declared to return XPathFactory.
-                throw new ClassCastException(returnType
-                            + " cannot be cast to " + SERVICE_CLASS);
-            }
-        } catch (ClassCastException e) {
-            throw new XPathFactoryConfigurationException(e);
-        } catch (NoSuchMethodException exc) {
-            return null;
-        } catch (Exception exc) {
-            return null;
-        }
-    }
 
     // Call isObjectModelSupportedBy with initial context.
     private boolean isObjectModelSupportedBy(final XPathFactory factory,
--- a/src/java.xml/share/classes/jdk/xml/internal/JdkXmlFeatures.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.xml/share/classes/jdk/xml/internal/JdkXmlFeatures.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, 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
@@ -26,6 +26,7 @@
 package jdk.xml.internal;
 
 import javax.xml.XMLConstants;
+import static jdk.xml.internal.JdkXmlUtils.OVERRIDE_PARSER;
 import static jdk.xml.internal.JdkXmlUtils.SP_USE_CATALOG;
 import static jdk.xml.internal.JdkXmlUtils.RESET_SYMBOL_TABLE;
 
@@ -36,6 +37,13 @@
 public class JdkXmlFeatures {
     public static final String ORACLE_JAXP_PROPERTY_PREFIX =
         "http://www.oracle.com/xml/jaxp/properties/";
+
+    public static final String XML_FEATURE_MANAGER =
+            ORACLE_JAXP_PROPERTY_PREFIX + "XmlFeatureManager";
+
+    public static final String ORACLE_FEATURE_SERVICE_MECHANISM =
+            "http://www.oracle.com/feature/use-service-mechanism";
+
     /**
      * Feature enableExtensionFunctions
      */
@@ -56,22 +64,37 @@
          * FSP: extension function is enforced by FSP. When FSP is on, extension
          * function is disabled.
          */
-        ENABLE_EXTENSION_FUNCTION(ORACLE_ENABLE_EXTENSION_FUNCTION,
-                SP_ENABLE_EXTENSION_FUNCTION_SPEC, true, false, true, true),
+        ENABLE_EXTENSION_FUNCTION(ORACLE_ENABLE_EXTENSION_FUNCTION, SP_ENABLE_EXTENSION_FUNCTION_SPEC,
+                ORACLE_ENABLE_EXTENSION_FUNCTION, SP_ENABLE_EXTENSION_FUNCTION,
+                true, false, true, true),
         /**
          * The {@link javax.xml.XMLConstants.USE_CATALOG} feature.
          * FSP: USE_CATALOG is not enforced by FSP.
          */
-        USE_CATALOG(PROPERTY_USE_CATALOG, SP_USE_CATALOG, true, false, true, false),
+        USE_CATALOG(PROPERTY_USE_CATALOG, SP_USE_CATALOG,
+                null, null,
+                true, false, true, false),
 
         /**
          * Feature resetSymbolTable
          * FSP: RESET_SYMBOL_TABLE_FEATURE is not enforced by FSP.
          */
-        RESET_SYMBOL_TABLE_FEATURE(RESET_SYMBOL_TABLE, RESET_SYMBOL_TABLE, false, false, true, false);
+        RESET_SYMBOL_TABLE_FEATURE(RESET_SYMBOL_TABLE, RESET_SYMBOL_TABLE,
+                null, null,
+                false, false, true, false),
+
+        /**
+         * Feature overrideDefaultParser
+         * FSP: not enforced by FSP.
+         */
+        JDK_OVERRIDE_PARSER(OVERRIDE_PARSER, OVERRIDE_PARSER,
+                ORACLE_FEATURE_SERVICE_MECHANISM, ORACLE_FEATURE_SERVICE_MECHANISM,
+                false, false, true, false);
 
         private final String name;
         private final String nameSP;
+        private final String nameOld;
+        private final String nameOldSP;
         private final boolean valueDefault;
         private final boolean valueEnforced;
         private final boolean hasSystem;
@@ -81,15 +104,20 @@
          * Constructs an XmlFeature instance.
          * @param name the name of the feature
          * @param nameSP the name of the System Property
+         * @param nameOld the name of the corresponding legacy property
+         * @param nameOldSP the system property of the legacy property
          * @param value the value of the feature
          * @param hasSystem a flag to indicate whether the feature is supported
          * @param enforced a flag indicating whether the feature is
          * FSP (Feature_Secure_Processing) enforced
          * with a System property
          */
-        XmlFeature(String name, String nameSP, boolean value, boolean valueEnforced, boolean hasSystem, boolean enforced) {
+        XmlFeature(String name, String nameSP, String nameOld, String nameOldSP,
+                boolean value, boolean valueEnforced, boolean hasSystem, boolean enforced) {
             this.name = name;
             this.nameSP = nameSP;
+            this.nameOld = nameOld;
+            this.nameOldSP = nameOldSP;
             this.valueDefault = value;
             this.valueEnforced = valueEnforced;
             this.hasSystem = hasSystem;
@@ -103,7 +131,8 @@
          * otherwise
          */
         boolean equalsPropertyName(String propertyName) {
-            return name.equals(propertyName);
+            return name.equals(propertyName) ||
+                    (nameOld != null && nameOld.equals(propertyName));
         }
 
         /**
@@ -125,6 +154,15 @@
         }
 
         /**
+         * Returns the name of the legacy System Property.
+         *
+         * @return the name of the legacy System Property
+         */
+        String systemPropertyOld() {
+            return nameOldSP;
+        }
+
+        /**
          * Returns the default value of the property.
          * @return the default value of the property
          */
@@ -159,30 +197,6 @@
     }
 
     /**
-     * Maps old property names with the new ones. This map is used to keep track of
-     * name changes so that old or incorrect names continue to be supported for compatibility.
-     */
-    public static enum NameMap {
-
-        ENABLE_EXTENSION_FUNCTION(SP_ENABLE_EXTENSION_FUNCTION_SPEC, SP_ENABLE_EXTENSION_FUNCTION);
-
-        final String newName;
-        final String oldName;
-
-        NameMap(String newName, String oldName) {
-            this.newName = newName;
-            this.oldName = oldName;
-        }
-
-        String getOldName(String newName) {
-            if (newName.equals(this.newName)) {
-                return oldName;
-            }
-            return null;
-        }
-    }
-
-    /**
      * States of the settings of a property, in the order: default value, value
      * set by FEATURE_SECURE_PROCESSING, jaxp.properties file, jaxp system
      * properties, and jaxp api properties
@@ -207,12 +221,12 @@
     /**
      * Values of the features
      */
-    private boolean[] featureValues;
+    private final boolean[] featureValues;
 
     /**
      * States of the settings for each property
      */
-    private State[] states;
+    private final State[] states;
 
     /**
      * Flag indicating if secure processing is set
@@ -349,14 +363,11 @@
      */
     private void readSystemProperties() {
         for (XmlFeature feature : XmlFeature.values()) {
-            getSystemProperty(feature, feature.systemProperty());
             if (!getSystemProperty(feature, feature.systemProperty())) {
                 //if system property is not found, try the older form if any
-                for (NameMap nameMap : NameMap.values()) {
-                    String oldName = nameMap.getOldName(feature.systemProperty());
-                    if (oldName != null) {
-                        getSystemProperty(feature, oldName);
-                    }
+                String oldName = feature.systemPropertyOld();
+                if (oldName != null) {
+                    getSystemProperty(feature, oldName);
                 }
             }
         }
@@ -367,6 +378,7 @@
      *
      * @param property the type of the property
      * @param sysPropertyName the name of system property
+     * @return true if the system property is found, false otherwise
      */
     private boolean getSystemProperty(XmlFeature feature, String sysPropertyName) {
         try {
--- a/src/java.xml/share/classes/jdk/xml/internal/JdkXmlUtils.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/java.xml/share/classes/jdk/xml/internal/JdkXmlUtils.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -22,16 +22,26 @@
  * or visit www.oracle.com if you need additional information or have any
  * questions.
  */
-
 package jdk.xml.internal;
 
 import com.sun.org.apache.xalan.internal.utils.XMLSecurityManager;
+import com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl;
+import com.sun.org.apache.xerces.internal.impl.Constants;
+import com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl;
+import com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl;
 import com.sun.org.apache.xerces.internal.util.ParserConfigurationSettings;
 import com.sun.org.apache.xerces.internal.xni.parser.XMLComponentManager;
 import com.sun.org.apache.xerces.internal.xni.parser.XMLConfigurationException;
 import javax.xml.XMLConstants;
 import javax.xml.catalog.CatalogFeatures;
 import javax.xml.catalog.CatalogFeatures.Feature;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.parsers.SAXParserFactory;
+import javax.xml.transform.TransformerConfigurationException;
+import javax.xml.transform.sax.SAXTransformerFactory;
+import org.w3c.dom.Document;
+import org.xml.sax.SAXException;
 import org.xml.sax.SAXNotRecognizedException;
 import org.xml.sax.SAXNotSupportedException;
 import org.xml.sax.XMLReader;
@@ -40,6 +50,18 @@
  * Constants for use across JAXP processors.
  */
 public class JdkXmlUtils {
+    private static final String DOM_FACTORY_ID = "javax.xml.parsers.DocumentBuilderFactory";
+    private static final String SAX_FACTORY_ID = "javax.xml.parsers.SAXParserFactory";
+    private static final String SAX_DRIVER = "org.xml.sax.driver";
+
+    /**
+     * Xerces features
+     */
+    public static final String NAMESPACES_FEATURE =
+        Constants.SAX_FEATURE_PREFIX + Constants.NAMESPACES_FEATURE;
+    public static final String NAMESPACE_PREFIXES_FEATURE =
+        Constants.SAX_FEATURE_PREFIX + Constants.NAMESPACE_PREFIXES_FEATURE;
+
 
     /**
      * Catalog features
@@ -52,12 +74,20 @@
     public final static String CATALOG_RESOLVE = CatalogFeatures.Feature.RESOLVE.getPropertyName();
 
     /**
-     * Reset SymbolTable feature
-     * System property name is identical to feature name
+     * Reset SymbolTable feature System property name is identical to feature
+     * name
      */
     public final static String RESET_SYMBOL_TABLE = "jdk.xml.resetSymbolTable";
 
     /**
+     * jdk.xml.overrideDefaultParser: enables the use of a 3rd party's parser
+     * implementation to override the system-default parser.
+     */
+    public static final String OVERRIDE_PARSER = "jdk.xml.overrideDefaultParser";
+    public static final boolean OVERRIDE_PARSER_DEFAULT = SecuritySupport.getJAXPSystemProperty(
+                    Boolean.class, OVERRIDE_PARSER, "false");
+
+    /**
      * Values for a feature
      */
     public static final String FEATURE_TRUE = "true";
@@ -75,7 +105,6 @@
     public static final boolean RESET_SYMBOL_TABLE_DEFAULT
             = SecuritySupport.getJAXPSystemProperty(Boolean.class, RESET_SYMBOL_TABLE, "false");
 
-
     /**
      * JDK features (will be consolidated in the next major feature revamp
      */
@@ -84,6 +113,11 @@
             = SecuritySupport.getJAXPSystemProperty(Integer.class, CDATA_CHUNK_SIZE, "0");
 
     /**
+     * The system-default factory
+     */
+    private static final SAXParserFactory defaultSAXFactory = getSAXFactory(false);
+
+    /**
      * Returns the value.
      *
      * @param value the specified value
@@ -227,4 +261,153 @@
             }
         }
     }
+
+    /**
+     * Returns an XMLReader instance. If overrideDefaultParser is requested, use
+     * SAXParserFactory or XMLReaderFactory, otherwise use the system-default
+     * SAXParserFactory to locate an XMLReader.
+     *
+     * @param overrideDefaultParser a flag indicating whether a 3rd party's
+     * parser implementation may be used to override the system-default one
+     * @param secureProcessing a flag indicating whether secure processing is
+     * requested
+     * @param useXMLReaderFactory a flag indicating when the XMLReader should be
+     * created using XMLReaderFactory. True is a compatibility mode that honors
+     * the property org.xml.sax.driver (see JDK-6490921).
+     * @return an XMLReader instance
+     */
+    public static XMLReader getXMLReader(boolean overrideDefaultParser,
+            boolean secureProcessing) {
+        SAXParserFactory saxFactory;
+        XMLReader reader = null;
+        String spSAXDriver = SecuritySupport.getSystemProperty(SAX_DRIVER);
+        if (spSAXDriver != null) {
+            reader = getXMLReaderWXMLReaderFactory();
+        } else if (overrideDefaultParser) {
+            reader = getXMLReaderWSAXFactory(overrideDefaultParser);
+        }
+
+        if (reader != null) {
+            if (secureProcessing) {
+                try {
+                    reader.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, secureProcessing);
+                } catch (SAXException e) {
+                    XMLSecurityManager.printWarning(reader.getClass().getName(),
+                            XMLConstants.FEATURE_SECURE_PROCESSING, e);
+                }
+            }
+            try {
+                reader.setFeature(NAMESPACES_FEATURE, true);
+                reader.setFeature(NAMESPACE_PREFIXES_FEATURE, false);
+            } catch (SAXException se) {
+                // older version of a parser
+            }
+            return reader;
+        }
+
+        // use the system-default
+        saxFactory = defaultSAXFactory;
+
+        try {
+            reader = saxFactory.newSAXParser().getXMLReader();
+        } catch (ParserConfigurationException | SAXException ex) {
+            // shall not happen with the system-default reader
+        }
+        return reader;
+    }
+
+    /**
+     * Creates a system-default DOM Document.
+     *
+     * @return a DOM Document instance
+     */
+    public static Document getDOMDocument() {
+        try {
+            DocumentBuilderFactory dbf = JdkXmlUtils.getDOMFactory(false);
+            return dbf.newDocumentBuilder().newDocument();
+        } catch (ParserConfigurationException pce) {
+            // can never happen with the system-default configuration
+        }
+        return null;
+    }
+
+    /**
+     * Returns a DocumentBuilderFactory instance.
+     *
+     * @param overrideDefaultParser a flag indicating whether the system-default
+     * implementation may be overridden. If the system property of the
+     * DOM factory ID is set, override is always allowed.
+     *
+     * @return a DocumentBuilderFactory instance.
+     */
+    public static DocumentBuilderFactory getDOMFactory(boolean overrideDefaultParser) {
+        boolean override = overrideDefaultParser;
+        String spDOMFactory = SecuritySupport.getJAXPSystemProperty(DOM_FACTORY_ID);
+
+        if (spDOMFactory != null && System.getSecurityManager() == null) {
+            override = true;
+        }
+        DocumentBuilderFactory dbf
+                = !override
+                        ? new DocumentBuilderFactoryImpl()
+                        : DocumentBuilderFactory.newInstance();
+        dbf.setNamespaceAware(true);
+        // false is the default setting. This step here is for compatibility
+        dbf.setValidating(false);
+        return dbf;
+    }
+
+    /**
+     * Returns a SAXParserFactory instance.
+     *
+     * @param overrideDefaultParser a flag indicating whether the system-default
+     * implementation may be overridden. If the system property of the
+     * DOM factory ID is set, override is always allowed.
+     *
+     * @return a SAXParserFactory instance.
+     */
+    public static SAXParserFactory getSAXFactory(boolean overrideDefaultParser) {
+        boolean override = overrideDefaultParser;
+        String spSAXFactory = SecuritySupport.getJAXPSystemProperty(SAX_FACTORY_ID);
+        if (spSAXFactory != null && System.getSecurityManager() == null) {
+            override = true;
+        }
+
+        SAXParserFactory factory
+                = !override
+                        ? new SAXParserFactoryImpl()
+                        : SAXParserFactory.newInstance();
+        factory.setNamespaceAware(true);
+        return factory;
+    }
+
+    public static SAXTransformerFactory getSAXTransformFactory(boolean overrideDefaultParser) {
+        SAXTransformerFactory tf = overrideDefaultParser
+                ? (SAXTransformerFactory) SAXTransformerFactory.newInstance()
+                : (SAXTransformerFactory) new TransformerFactoryImpl();
+        try {
+            tf.setFeature(OVERRIDE_PARSER, overrideDefaultParser);
+        } catch (TransformerConfigurationException ex) {
+            // ignore since it'd never happen with the JDK impl.
+        }
+        return tf;
+    }
+
+    private static XMLReader getXMLReaderWSAXFactory(boolean overrideDefaultParser) {
+        SAXParserFactory saxFactory = getSAXFactory(overrideDefaultParser);
+        try {
+            return saxFactory.newSAXParser().getXMLReader();
+        } catch (ParserConfigurationException | SAXException ex) {
+            return getXMLReaderWXMLReaderFactory();
+        }
+    }
+
+    @SuppressWarnings("deprecation")
+    private static XMLReader getXMLReaderWXMLReaderFactory() {
+        try {
+            return org.xml.sax.helpers.XMLReaderFactory.createXMLReader();
+        } catch (SAXException ex1) {
+        }
+        return null;
+    }
 }
--- a/src/jdk.attach/share/classes/sun/tools/attach/HotSpotVirtualMachine.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/jdk.attach/share/classes/sun/tools/attach/HotSpotVirtualMachine.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2018, 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
@@ -86,6 +86,10 @@
     private void loadAgentLibrary(String agentLibrary, boolean isAbsolute, String options)
         throws AgentLoadException, AgentInitializationException, IOException
     {
+        if (agentLibrary == null) {
+            throw new NullPointerException("agentLibrary cannot be null");
+        }
+
         String msgPrefix = "return code: ";
         InputStream in = execute("load",
                                  agentLibrary,
@@ -131,6 +135,10 @@
     public void loadAgent(String agent, String options)
         throws AgentLoadException, AgentInitializationException, IOException
     {
+        if (agent == null) {
+            throw new NullPointerException("agent cannot be null");
+        }
+
         String args = agent;
         if (options != null) {
             args = args + "=" + options;
--- a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/ArgumentAttr.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/ArgumentAttr.java	Fri Jan 19 09:32:10 2018 -0800
@@ -366,7 +366,9 @@
 
         @Override
         Type speculativeType(Symbol msym, MethodResolutionPhase phase) {
-            if (pertinentToApplicability) {
+            if (notPertinentToApplicability.contains(msym)) {
+                return super.speculativeType(msym, phase);
+            } else {
                 for (Map.Entry<ResultInfo, Type> _entry : speculativeTypes.entrySet()) {
                     DeferredAttrContext deferredAttrContext = _entry.getKey().checkContext.deferredAttrContext();
                     if (deferredAttrContext.phase == phase && deferredAttrContext.msym == msym) {
@@ -374,14 +376,14 @@
                     }
                 }
                 return Type.noType;
-            } else {
-                return super.speculativeType(msym, phase);
             }
         }
 
         @Override
         JCTree speculativeTree(DeferredAttrContext deferredAttrContext) {
-            return pertinentToApplicability ? speculativeTree : super.speculativeTree(deferredAttrContext);
+            return notPertinentToApplicability.contains(deferredAttrContext.msym) ?
+                    super.speculativeTree(deferredAttrContext) :
+                    speculativeTree;
         }
 
         /**
--- a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/DeferredAttr.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/DeferredAttr.java	Fri Jan 19 09:32:10 2018 -0800
@@ -200,7 +200,7 @@
         public JCExpression tree;
         Env<AttrContext> env;
         AttrMode mode;
-        boolean pertinentToApplicability = true;
+        Set<Symbol> notPertinentToApplicability = new HashSet<>();
         SpeculativeCache speculativeCache;
 
         DeferredType(JCExpression tree, Env<AttrContext> env) {
@@ -319,7 +319,7 @@
                     resultInfo.checkContext.deferredAttrContext();
             Assert.check(deferredAttrContext != emptyDeferredAttrContext);
             if (deferredStuckPolicy.isStuck()) {
-                pertinentToApplicability = false;
+                notPertinentToApplicability.add(deferredAttrContext.msym);
                 deferredAttrContext.addDeferredAttrNode(this, resultInfo, deferredStuckPolicy);
                 return Type.noType;
             } else {
--- a/src/jdk.compiler/share/classes/com/sun/tools/javac/parser/JavacParser.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/parser/JavacParser.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2018, 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
@@ -3403,8 +3403,12 @@
     Name typeName() {
         int pos = token.pos;
         Name name = ident();
-        if (isRestrictedLocalVarTypeName(name)) {
-            reportSyntaxError(pos, "var.not.allowed", name);
+        if (name == names.var) {
+            if (Feature.LOCAL_VARIABLE_TYPE_INFERENCE.allowedInSource(source)) {
+                reportSyntaxError(pos, "var.not.allowed", name);
+            } else {
+                warning(pos, "var.not.allowed");
+            }
         }
         return name;
     }
--- a/src/jdk.compiler/share/classes/com/sun/tools/javac/resources/compiler.properties	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/resources/compiler.properties	Fri Jan 19 09:32:10 2018 -0800
@@ -1212,6 +1212,9 @@
     ''{0}'' not allowed here\n\
     as of release 10, ''{0}'' is a restricted local variable type and cannot be used for type declarations
 
+compiler.warn.var.not.allowed=\
+    as of release 10, ''var'' is a restricted local variable type and cannot be used for type declarations
+
 # 0: name (variable), 1: message segment
 compiler.err.cant.infer.local.var.type=\
     cannot infer type for local variable {0}\n\
--- a/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11KeyAgreement.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11KeyAgreement.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2017, 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
@@ -69,6 +69,17 @@
     // KeyAgreement from SunJCE as fallback for > 2 party agreement
     private KeyAgreement multiPartyAgreement;
 
+    private static class AllowKDF {
+
+        private static final boolean VALUE = getValue();
+
+        private static boolean getValue() {
+            return AccessController.doPrivileged(
+                (PrivilegedAction<Boolean>)
+                () -> Boolean.getBoolean("jdk.crypto.KeyAgreement.legacyKDF"));
+        }
+    }
+
     P11KeyAgreement(Token token, String algorithm, long mechanism) {
         super();
         this.token = token;
@@ -260,6 +271,7 @@
         if (algorithm == null) {
             throw new NoSuchAlgorithmException("Algorithm must not be null");
         }
+
         if (algorithm.equals("TlsPremasterSecret")) {
             // For now, only perform native derivation for TlsPremasterSecret
             // as that is required for FIPS compliance.
@@ -268,6 +280,14 @@
             // (bug not yet filed).
             return nativeGenerateSecret(algorithm);
         }
+
+        if (!algorithm.equalsIgnoreCase("TlsPremasterSecret") &&
+            !AllowKDF.VALUE) {
+
+            throw new NoSuchAlgorithmException("Unsupported secret key "
+                                               + "algorithm: " + algorithm);
+        }
+
         byte[] secret = engineGenerateSecret();
         // Maintain compatibility for SunJCE:
         // verify secret length is sensible for algorithm / truncate
--- a/src/jdk.hotspot.agent/share/classes/sun/jvm/hotspot/CommandProcessor.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/jdk.hotspot.agent/share/classes/sun/jvm/hotspot/CommandProcessor.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2018, 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
@@ -1607,7 +1607,9 @@
                             if (!all) return;
                         }
                     }
-                    out.println("Couldn't find thread " + name);
+                    if (!all) {
+                        out.println("Couldn't find thread " + name);
+                    }
                 }
             }
         },
--- a/src/jdk.hotspot.agent/share/classes/sun/jvm/hotspot/oops/CompiledICHolder.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/jdk.hotspot.agent/share/classes/sun/jvm/hotspot/oops/CompiledICHolder.java	Fri Jan 19 09:32:10 2018 -0800
@@ -40,10 +40,10 @@
   }
 
   private static synchronized void initialize(TypeDataBase db) throws WrongTypeException {
-    Type type    = db.lookupType("CompiledICHolder");
-    holderMethod = new MetadataField(type.getAddressField("_holder_method"), 0);
-    holderKlass  = new MetadataField(type.getAddressField("_holder_klass"), 0);
-    headerSize   = type.getSize();
+    Type type      = db.lookupType("CompiledICHolder");
+    holderMetadata = new MetadataField(type.getAddressField("_holder_metadata"), 0);
+    holderKlass    = new MetadataField(type.getAddressField("_holder_klass"), 0);
+    headerSize     = type.getSize();
   }
 
   public CompiledICHolder(Address addr) {
@@ -55,12 +55,12 @@
   private static long headerSize;
 
   // Fields
-  private static MetadataField holderMethod;
+  private static MetadataField holderMetadata;
   private static MetadataField holderKlass;
 
   // Accessors for declared fields
-  public Method getHolderMethod() { return (Method) holderMethod.getValue(this); }
-  public Klass  getHolderKlass()  { return (Klass)  holderKlass.getValue(this); }
+  public Metadata getHolderMetadata() { return (Metadata) holderMetadata.getValue(this); }
+  public Klass    getHolderKlass()    { return (Klass)    holderKlass.getValue(this); }
 
   public void printValueOn(PrintStream tty) {
     tty.print("CompiledICHolder");
--- a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/DocFilesHandlerImpl.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/DocFilesHandlerImpl.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2017, 2018, 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
@@ -25,10 +25,17 @@
 
 package jdk.javadoc.internal.doclets.formats.html;
 
+import com.sun.source.doctree.AttributeTree;
+import com.sun.source.doctree.AttributeTree.ValueKind;
+import com.sun.source.doctree.DocRootTree;
 import com.sun.source.doctree.DocTree;
 import com.sun.source.doctree.EndElementTree;
+import com.sun.source.doctree.LinkTree;
 import com.sun.source.doctree.StartElementTree;
 import com.sun.source.doctree.TextTree;
+import com.sun.source.util.SimpleDocTreeVisitor;
+import com.sun.tools.doclint.HtmlTag;
+import com.sun.tools.doclint.HtmlTag.Attr;
 import jdk.javadoc.internal.doclets.formats.html.markup.HtmlTree;
 import jdk.javadoc.internal.doclets.toolkit.Content;
 import jdk.javadoc.internal.doclets.toolkit.DocFileElement;
@@ -123,13 +130,14 @@
                     configuration.messages.warning("doclet.Copy_Overwrite_warning",
                             srcfile.getPath(), dstdir.getPath());
                 } else {
+                    if (Utils.toLowerCase(srcfile.getPath()).endsWith(".html")) {
+                        if (handleHtmlFile(srcfile, dstDocPath)) {
+                            continue;
+                        }
+                    }
                     configuration.messages.notice("doclet.Copying_File_0_To_Dir_1",
                             srcfile.getPath(), dstdir.getPath());
-                    if (Utils.toLowerCase(srcfile.getPath()).endsWith(".html")) {
-                        handleHtmlFile(srcfile, dstDocPath);
-                    } else {
-                        destfile.copyFile(srcfile);
-                    }
+                    destfile.copyFile(srcfile);
                 }
             } else if (srcfile.isDirectory()) {
                 if (configuration.copydocfilesubdirs
@@ -141,19 +149,23 @@
         }
     }
 
-    private void handleHtmlFile(DocFile srcfile, DocPath dstPath) throws DocFileIOException {
+    private boolean handleHtmlFile(DocFile srcfile, DocPath dstPath) throws DocFileIOException {
+        Utils utils = configuration.utils;
+        FileObject fileObject = srcfile.getFileObject();
+        DocFileElement dfElement = new DocFileElement(element, fileObject);
+
+        if (shouldPassThrough(utils.getPreamble(dfElement))) {
+            return false;
+        }
+
         DocPath dfilePath = dstPath.resolve(srcfile.getName());
         HtmlDocletWriter docletWriter = new DocFileWriter(configuration, dfilePath, element);
-
-        Utils utils = configuration.utils;
+        configuration.messages.notice("doclet.Generating_0", docletWriter.filename);
 
-        FileObject fileObject = srcfile.getFileObject();
-        DocFileElement dfElement = new DocFileElement(element, fileObject);
         String title = getWindowTitle(docletWriter, dfElement).trim();
         HtmlTree htmlContent = docletWriter.getBody(true, title);
         docletWriter.addTop(htmlContent);
         docletWriter.addNavLinks(true, htmlContent);
-
         List<? extends DocTree> fullBody = utils.getFullBody(dfElement);
         Content bodyContent = docletWriter.commentTagsToContent(null, dfElement, fullBody, false);
 
@@ -163,6 +175,69 @@
         docletWriter.addNavLinks(false, htmlContent);
         docletWriter.addBottom(htmlContent);
         docletWriter.printHtmlDocument(Collections.emptyList(), false, htmlContent);
+        return true;
+    }
+
+
+    private boolean shouldPassThrough(List<? extends DocTree> dtrees) {
+        SimpleDocTreeVisitor<Boolean, Boolean> check = new SimpleDocTreeVisitor<Boolean, Boolean>() {
+            @Override
+            public Boolean visitStartElement(StartElementTree node, Boolean p) {
+                if (Utils.toLowerCase(node.getName().toString()).equals((Attr.STYLE.getText()))) {
+                    return true;
+                }
+                if (Utils.toLowerCase(node.getName().toString()).equals(HtmlTag.LINK.getText())) {
+                    for (DocTree dt : node.getAttributes()) {
+                        if (this.visit(dt, true))
+                            return true;
+                    }
+                }
+                return false;
+            }
+
+            @Override
+            public Boolean visitAttribute(AttributeTree node, Boolean p) {
+                if (p == null || p == false) {
+                    return false;
+                }
+                if (Utils.toLowerCase(node.getName().toString()).equals("rel")) {
+                    for (DocTree dt :  node.getValue()) {
+                        Boolean found = new SimpleDocTreeVisitor<Boolean, ValueKind>() {
+
+                            @Override
+                            public Boolean visitText(TextTree node, ValueKind valueKind) {
+                                switch (valueKind) {
+                                    case EMPTY:
+                                        return false;
+                                    default:
+                                        return Utils.toLowerCase(node.getBody()).equals("stylesheet");
+                                }
+                            }
+
+                            @Override
+                            protected Boolean defaultAction(DocTree node, ValueKind valueKind) {
+                                return false;
+                            }
+
+                        }.visit(dt, node.getValueKind());
+
+                        if (found)
+                            return true;
+                    }
+                }
+                return false;
+            }
+
+            @Override
+            protected Boolean defaultAction(DocTree node, Boolean p) {
+                return false;
+            }
+        };
+        for (DocTree dt : dtrees) {
+            if (check.visit(dt, false))
+                return true;
+        }
+        return false;
     }
 
     private String getWindowTitle(HtmlDocletWriter docletWriter, Element element) {
--- a/src/jdk.jshell/share/classes/jdk/jshell/Eval.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/jdk.jshell/share/classes/jdk/jshell/Eval.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 2018, 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
@@ -36,6 +36,7 @@
 import com.sun.source.tree.ArrayTypeTree;
 import com.sun.source.tree.AssignmentTree;
 import com.sun.source.tree.ClassTree;
+import com.sun.source.tree.ExpressionStatementTree;
 import com.sun.source.tree.ExpressionTree;
 import com.sun.source.tree.IdentifierTree;
 import com.sun.source.tree.MethodTree;
@@ -43,6 +44,7 @@
 import com.sun.source.tree.NewClassTree;
 import com.sun.source.tree.Tree;
 import com.sun.source.tree.VariableTree;
+import com.sun.source.util.TreeScanner;
 import com.sun.tools.javac.tree.JCTree;
 import com.sun.tools.javac.tree.Pretty;
 import java.io.IOException;
@@ -52,6 +54,8 @@
 import java.util.LinkedHashSet;
 import java.util.Set;
 import jdk.jshell.ExpressionToTypeInfo.ExpressionInfo;
+import jdk.jshell.ExpressionToTypeInfo.ExpressionInfo.AnonymousDescription;
+import jdk.jshell.ExpressionToTypeInfo.ExpressionInfo.AnonymousDescription.VariableDesc;
 import jdk.jshell.Key.ErroneousKey;
 import jdk.jshell.Key.MethodKey;
 import jdk.jshell.Key.TypeDeclKey;
@@ -60,6 +64,7 @@
 import jdk.jshell.TaskFactory.AnalyzeTask;
 import jdk.jshell.TaskFactory.BaseTask;
 import jdk.jshell.TaskFactory.ParseTask;
+import jdk.jshell.Util.Pair;
 import jdk.jshell.Wrap.CompoundWrap;
 import jdk.jshell.Wrap.Range;
 import jdk.jshell.Snippet.Status;
@@ -74,6 +79,7 @@
 import static java.util.stream.Collectors.toList;
 import static java.util.stream.Collectors.toSet;
 import static java.util.Collections.singletonList;
+import com.sun.tools.javac.code.Symbol.TypeSymbol;
 import static jdk.internal.jshell.debug.InternalDebugControl.DBG_GEN;
 import static jdk.jshell.Util.DOIT_METHOD_NAME;
 import static jdk.jshell.Util.PREFIX_PATTERN;
@@ -98,6 +104,11 @@
 
     private int varNumber = 0;
 
+    /* The number of anonymous innerclasses seen so far. Used to generate unique
+     * names of these classes.
+     */
+    private int anonCount = 0;
+
     private final JShell state;
 
     // The set of names of methods on Object
@@ -203,7 +214,7 @@
                 case VARIABLE:
                     return processVariables(userSource, units, compileSourceInt, pt);
                 case EXPRESSION_STATEMENT:
-                    return processExpression(userSource, compileSourceInt);
+                    return processExpression(userSource, unitTree, compileSourceInt, pt);
                 case CLASS:
                     return processClass(userSource, unitTree, compileSourceInt, SubKind.CLASS_SUBKIND, pt);
                 case ENUM:
@@ -285,15 +296,19 @@
             String name = vt.getName().toString();
             String typeName;
             String fullTypeName;
+            String displayType;
+            boolean hasEnhancedType = false;
             TreeDependencyScanner tds = new TreeDependencyScanner();
             Wrap typeWrap;
             Wrap anonDeclareWrap = null;
             Wrap winit = null;
+            boolean enhancedDesugaring = false;
+            Set<String> anonymousClasses = Collections.emptySet();
             StringBuilder sbBrackets = new StringBuilder();
             Tree baseType = vt.getType();
             if (baseType != null) {
                 tds.scan(baseType); // Not dependent on initializer
-                fullTypeName = typeName = EvalPretty.prettyExpr((JCTree) vt.getType(), false);
+                fullTypeName = displayType = typeName = EvalPretty.prettyExpr((JCTree) vt.getType(), false);
                 while (baseType instanceof ArrayTypeTree) {
                     //TODO handle annotations too
                     baseType = ((ArrayTypeTree) baseType).getType();
@@ -311,83 +326,27 @@
                     Range rinit = dis.treeToRange(init);
                     String initCode = rinit.part(compileSource);
                     ExpressionInfo ei =
-                            ExpressionToTypeInfo.localVariableTypeForInitializer(initCode, state);
-                    typeName = ei == null ? "java.lang.Object" : ei.typeName;
-                    fullTypeName = ei == null ? "java.lang.Object" : ei.fullTypeName;
-                    if (ei != null && init.getKind() == Tree.Kind.NEW_CLASS &&
-                        ((NewClassTree) init).getClassBody() != null) {
-                        NewClassTree nct = (NewClassTree) init;
-                        StringBuilder constructor = new StringBuilder();
-                        constructor.append(fullTypeName).append("(");
-                        String sep = "";
-                        if (ei.enclosingInstanceType != null) {
-                            constructor.append(ei.enclosingInstanceType);
-                            constructor.append(" encl");
-                            sep = ", ";
-                        }
-                        int idx = 0;
-                        for (String type : ei.parameterTypes) {
-                            constructor.append(sep);
-                            constructor.append(type);
-                            constructor.append(" ");
-                            constructor.append("arg" + idx++);
-                            sep = ", ";
-                        }
-                        if (ei.enclosingInstanceType != null) {
-                            constructor.append(") { encl.super (");
-                        } else {
-                            constructor.append(") { super (");
-                        }
-                        sep = "";
-                        for (int i = 0; i < idx; i++) {
-                            constructor.append(sep);
-                            constructor.append("arg" + i++);
-                            sep = ", ";
-                        }
-                        constructor.append("); }");
-                        List<? extends Tree> members = nct.getClassBody().getMembers();
-                        Range bodyRange = dis.treeListToRange(members);
-                        Wrap bodyWrap;
+                            ExpressionToTypeInfo.localVariableTypeForInitializer(initCode, state, false);
+                    if (ei != null) {
+                        typeName = ei.declareTypeName;
+                        fullTypeName = ei.fullTypeName;
+                        displayType = ei.displayTypeName;
+
+                        hasEnhancedType = !typeName.equals(fullTypeName);
 
-                        if (bodyRange != null) {
-                            bodyWrap = Wrap.rangeWrap(compileSource, bodyRange);
-                        } else {
-                            bodyWrap = Wrap.simpleWrap(" ");
-                        }
-
-                        Range argRange = dis.treeListToRange(nct.getArguments());
-                        Wrap argWrap;
-
-                        if (argRange != null) {
-                            argWrap = Wrap.rangeWrap(compileSource, argRange);
-                        } else {
-                            argWrap = Wrap.simpleWrap(" ");
-                        }
+                        enhancedDesugaring = !ei.isPrimitiveType;
 
-                        if (ei.enclosingInstanceType != null) {
-                            Range enclosingRanges =
-                                    dis.treeToRange(nct.getEnclosingExpression());
-                            Wrap enclosingWrap = Wrap.rangeWrap(compileSource, enclosingRanges);
-                            argWrap = argRange != null ? new CompoundWrap(enclosingWrap,
-                                                                          Wrap.simpleWrap(","),
-                                                                          argWrap)
-                                                       : enclosingWrap;
-                        }
-                        Wrap hwrap = Wrap.simpleWrap("public static class " + fullTypeName +
-                                                     (ei.isClass ? " extends " : " implements ") +
-                                                     typeName + " { " + constructor);
-                        anonDeclareWrap = new CompoundWrap(hwrap, bodyWrap, Wrap.simpleWrap("}"));
-                        winit = new CompoundWrap("new " + fullTypeName + "(", argWrap, ")");
-
-                        String superType = typeName;
-
-                        typeName = fullTypeName;
-                        fullTypeName = ei.isClass ? "<anonymous class extending " + superType + ">"
-                                                  : "<anonymous class implementing " + superType + ">";
+                        Pair<Wrap, Wrap> anonymous2Member =
+                                anonymous2Member(ei, compileSource, rinit, dis, init);
+                        anonDeclareWrap = anonymous2Member.first;
+                        winit = anonymous2Member.second;
+                        anonymousClasses = ei.anonymousClasses.stream().map(ad -> ad.declareTypeName).collect(Collectors.toSet());
+                    } else {
+                        displayType = fullTypeName = typeName = "java.lang.Object";
                     }
                     tds.scan(init);
                 } else {
-                    fullTypeName = typeName = "java.lang.Object";
+                    displayType = fullTypeName = typeName = "java.lang.Object";
                 }
                 typeWrap = Wrap.identityWrap(typeName);
             }
@@ -411,17 +370,193 @@
             int nameEnd = nameStart + name.length();
             Range rname = new Range(nameStart, nameEnd);
             Wrap guts = Wrap.varWrap(compileSource, typeWrap, sbBrackets.toString(), rname,
-                                     winit, anonDeclareWrap);
-                        DiagList modDiag = modifierDiagnostics(vt.getModifiers(), dis, true);
+                                     winit, enhancedDesugaring, anonDeclareWrap);
+            DiagList modDiag = modifierDiagnostics(vt.getModifiers(), dis, true);
             Snippet snip = new VarSnippet(state.keyMap.keyForVariable(name), userSource, guts,
-                    name, subkind, fullTypeName,
+                    name, subkind, displayType, hasEnhancedType ? fullTypeName : null, anonymousClasses,
                     tds.declareReferences(), modDiag);
             snippets.add(snip);
         }
         return snippets;
     }
 
-    private List<Snippet> processExpression(String userSource, String compileSource) {
+    /**Convert anonymous classes in "init" to member classes, based
+     * on the additional information from ExpressionInfo.anonymousClasses.
+     *
+     * This means:
+     * -if the code in the anonymous class captures any variables from the
+     *  enclosing context, create fields for them
+     * -creating an explicit constructor that:
+     * --if the new class expression has a base/enclosing expression, make it an
+     *   explicit constructor parameter "encl" and use "encl.super" when invoking
+     *   the supertype constructor
+     * --if the (used) supertype constructor has any parameters, declare them
+     *   as explicit parameters of the constructor, and pass them to the super
+     *   constructor
+     * --if the code in the anonymous class captures any variables from the
+     *   enclosing context, make them an explicit paramters of the constructor
+     *   and assign to respective fields.
+     * --if there are any explicit fields with initializers in the anonymous class,
+     *   move the initializers at the end of the constructor (after the captured fields
+     *   are assigned, so that the initializers of these fields can use them).
+     * -from the captured variables fields, constructor, and existing members
+     *  (with cleared field initializers), create an explicit class that extends or
+     *  implements the supertype of the anonymous class.
+     *
+     * This method returns two wraps: the first contains the class declarations for the
+     * converted classes, the first one should be used instead of "init" in the variable
+     * declaration.
+     */
+    private Pair<Wrap, Wrap> anonymous2Member(ExpressionInfo ei,
+                                              String compileSource,
+                                              Range rinit,
+                                              TreeDissector dis,
+                                              Tree init) {
+        List<Wrap> anonymousDeclarations = new ArrayList<>();
+        List<Wrap> partitionedInit = new ArrayList<>();
+        int lastPos = rinit.begin;
+        com.sun.tools.javac.util.List<NewClassTree> toConvert =
+                ExpressionToTypeInfo.listAnonymousClassesToConvert(init);
+        com.sun.tools.javac.util.List<AnonymousDescription> descriptions =
+                ei.anonymousClasses;
+        while (toConvert.nonEmpty() && descriptions.nonEmpty()) {
+            NewClassTree node = toConvert.head;
+            AnonymousDescription ad = descriptions.head;
+
+            toConvert = toConvert.tail;
+            descriptions = descriptions.tail;
+
+            List<Object> classBodyParts = new ArrayList<>();
+            //declarations of the captured variables:
+            for (VariableDesc vd : ad.capturedVariables) {
+                classBodyParts.add(vd.type + " " + vd.name + ";\n");
+            }
+
+            List<Object> constructorParts = new ArrayList<>();
+            constructorParts.add(ad.declareTypeName + "(");
+            String sep = "";
+            //add the parameter for the base/enclosing expression, if any:
+            if (ad.enclosingInstanceType != null) {
+                constructorParts.add(ad.enclosingInstanceType + " encl");
+                sep = ", ";
+            }
+            int idx = 0;
+            //add parameters of the super constructor, if any:
+            for (String type : ad.parameterTypes) {
+                constructorParts.add(sep);
+                constructorParts.add(type + " " + "arg" + idx++);
+                sep = ", ";
+            }
+            //add parameters for the captured variables:
+            for (VariableDesc vd : ad.capturedVariables) {
+                constructorParts.add(sep);
+                constructorParts.add(vd.type + " " + "cap$" + vd.name);
+                sep = ", ";
+            }
+            //construct super constructor call:
+            if (ad.enclosingInstanceType != null) {
+                //if there's an enclosing instance, call super on it:
+                constructorParts.add(") { encl.super (");
+            } else {
+                constructorParts.add(") { super (");
+            }
+            sep = "";
+            for (int i = 0; i < idx; i++) {
+                constructorParts.add(sep);
+                constructorParts.add("arg" + i);
+                sep = ", ";
+            }
+            constructorParts.add(");");
+            //initialize the captured variables:
+            for (VariableDesc vd : ad.capturedVariables) {
+                constructorParts.add("this." + vd.name + " = " + "cap$" + vd.name + ";\n");
+            }
+            List<? extends Tree> members =
+                    node.getClassBody().getMembers();
+            for (Tree member : members) {
+                if (member.getKind() == Tree.Kind.VARIABLE) {
+                    VariableTree vt = (VariableTree) member;
+
+                    if (vt.getInitializer() != null) {
+                        //for variables with initializer, explicitly move the initializer
+                        //to the constructor after the captured variables as assigned
+                        //(the initializers would otherwise run too early):
+                        Range wholeVar = dis.treeToRange(vt);
+                        int name = ((JCTree) vt).pos;
+                        classBodyParts.add(new CompoundWrap(Wrap.rangeWrap(compileSource,
+                                                                      new Range(wholeVar.begin, name)),
+                                                       vt.getName().toString(),
+                                                       ";\n"));
+                        constructorParts.add(Wrap.rangeWrap(compileSource,
+                                                            new Range(name, wholeVar.end)));
+                        continue;
+                    }
+                }
+                classBodyParts.add(Wrap.rangeWrap(compileSource,
+                                             dis.treeToRange(member)));
+            }
+
+            constructorParts.add("}");
+
+            //construct the member class:
+            classBodyParts.add(new CompoundWrap(constructorParts.toArray()));
+
+            Wrap classBodyWrap = new CompoundWrap(classBodyParts.toArray());
+
+            anonymousDeclarations.add(new CompoundWrap("public static class ", ad.declareTypeName,
+                                         (ad.isClass ? " extends " : " implements "),
+                                         ad.superTypeName, " { ", classBodyWrap, "}"));
+
+            //change the new class expression to use the newly created member type:
+            Range argRange = dis.treeListToRange(node.getArguments());
+            Wrap argWrap;
+
+            if (argRange != null) {
+                argWrap = Wrap.rangeWrap(compileSource, argRange);
+            } else {
+                argWrap = Wrap.simpleWrap(" ");
+            }
+
+            if (ad.enclosingInstanceType != null) {
+                //if there's an enclosing expression, set it as the first parameter:
+                Range enclosingRanges =
+                        dis.treeToRange(node.getEnclosingExpression());
+                Wrap enclosingWrap = Wrap.rangeWrap(compileSource, enclosingRanges);
+                argWrap = argRange != null ? new CompoundWrap(enclosingWrap,
+                                                              Wrap.simpleWrap(","),
+                                                              argWrap)
+                                           : enclosingWrap;
+            }
+
+            Range current = dis.treeToRange(node);
+            String capturedArgs;
+            if (!ad.capturedVariables.isEmpty()) {
+                capturedArgs = (ad.parameterTypes.isEmpty() ? "" : ", ") +
+                               ad.capturedVariables.stream()
+                                                   .map(vd -> vd.name)
+                                                   .collect(Collectors.joining(","));
+            } else {
+                capturedArgs = "";
+            }
+            if (lastPos < current.begin)
+                partitionedInit.add(Wrap.rangeWrap(compileSource,
+                                                   new Range(lastPos, current.begin)));
+            partitionedInit.add(new CompoundWrap("new " + ad.declareTypeName + "(",
+                                                 argWrap,
+                                                 capturedArgs,
+                                                 ")"));
+            lastPos = current.end;
+        }
+
+        if (lastPos < rinit.end)
+            partitionedInit.add(Wrap.rangeWrap(compileSource, new Range(lastPos, rinit.end)));
+
+        return new Pair<>(new CompoundWrap(anonymousDeclarations.toArray()),
+                          new CompoundWrap(partitionedInit.toArray()));
+    }
+
+    private List<Snippet> processExpression(String userSource, Tree tree, String compileSource, ParseTask pt) {
+        ExpressionStatementTree expr = (ExpressionStatementTree) tree;
         String name = null;
         ExpressionInfo ei = ExpressionToTypeInfo.expressionInfo(compileSource, state);
         ExpressionTree assignVar;
@@ -453,10 +588,31 @@
                         name = "$" + ++varNumber;
                     }
                 }
-                guts = Wrap.tempVarWrap(compileSource, ei.accessibleTypeName, name);
+                TreeDissector dis = TreeDissector.createByFirstClass(pt);
+                ExpressionInfo varEI =
+                        ExpressionToTypeInfo.localVariableTypeForInitializer(compileSource, state, true);
+                String declareTypeName;
+                String fullTypeName;
+                String displayTypeName;
+                Set<String> anonymousClasses;
+                if (varEI != null) {
+                    declareTypeName = varEI.declareTypeName;
+                    fullTypeName = varEI.fullTypeName;
+                    displayTypeName = varEI.displayTypeName;
+
+                    Pair<Wrap, Wrap> anonymous2Member =
+                            anonymous2Member(varEI, compileSource, new Range(0, compileSource.length()), dis, expr.getExpression());
+                    guts = Wrap.tempVarWrap(anonymous2Member.second.wrapped(), declareTypeName, name, anonymous2Member.first);
+                    anonymousClasses = varEI.anonymousClasses.stream().map(ad -> ad.declareTypeName).collect(Collectors.toSet());
+                } else {
+                    declareTypeName = ei.accessibleTypeName;
+                    displayTypeName = fullTypeName = typeName;
+                    guts = Wrap.tempVarWrap(compileSource, declareTypeName, name, null);
+                    anonymousClasses = Collections.emptySet();
+                }
                 Collection<String> declareReferences = null; //TODO
                 snip = new VarSnippet(state.keyMap.keyForVariable(name), userSource, guts,
-                        name, SubKind.TEMP_VAR_EXPRESSION_SUBKIND, typeName, declareReferences, null);
+                        name, SubKind.TEMP_VAR_EXPRESSION_SUBKIND, displayTypeName, fullTypeName, anonymousClasses, declareReferences, null);
             } else {
                 guts = Wrap.methodReturnWrap(compileSource);
                 snip = new ExpressionSnippet(state.keyMap.keyForExpression(name, typeName), userSource, guts,
@@ -1059,4 +1215,7 @@
                 : new DiagList(new ModifierDiagnostic(list, fatal));
     }
 
+    String computeDeclareName(TypeSymbol ts) {
+        return Util.JSHELL_ANONYMOUS + "$" + Long.toUnsignedString(anonCount++);
+    }
 }
--- a/src/jdk.jshell/share/classes/jdk/jshell/ExpressionToTypeInfo.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/jdk.jshell/share/classes/jdk/jshell/ExpressionToTypeInfo.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2018, 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
@@ -25,12 +25,21 @@
 
 package jdk.jshell;
 
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+import java.util.function.Function;
+import javax.lang.model.element.Element;
+import javax.lang.model.element.ElementKind;
+import javax.lang.model.element.VariableElement;
 import com.sun.source.tree.ReturnTree;
 import com.sun.source.tree.ClassTree;
 import com.sun.source.tree.CompilationUnitTree;
 import com.sun.source.tree.ConditionalExpressionTree;
-import com.sun.source.tree.ExpressionStatementTree;
 import com.sun.source.tree.ExpressionTree;
+import com.sun.source.tree.IdentifierTree;
 import com.sun.source.tree.MethodInvocationTree;
 import com.sun.source.tree.MethodTree;
 import com.sun.source.tree.NewClassTree;
@@ -39,13 +48,21 @@
 import com.sun.source.tree.VariableTree;
 import com.sun.source.util.TreePath;
 import com.sun.source.util.TreePathScanner;
+import com.sun.source.util.TreeScanner;
 import com.sun.tools.javac.code.Flags;
 import com.sun.tools.javac.code.Symbol;
+import com.sun.tools.javac.code.Symbol.TypeSymbol;
 import com.sun.tools.javac.code.Symtab;
 import com.sun.tools.javac.code.Type;
 import com.sun.tools.javac.code.Types;
+import com.sun.tools.javac.tree.JCTree.JCClassDecl;
+import com.sun.tools.javac.tree.TreeInfo;
 import com.sun.tools.javac.util.List;
+import com.sun.tools.javac.util.ListBuffer;
+import jdk.jshell.ExpressionToTypeInfo.ExpressionInfo.AnonymousDescription;
+import jdk.jshell.ExpressionToTypeInfo.ExpressionInfo.AnonymousDescription.VariableDesc;
 import jdk.jshell.TaskFactory.AnalyzeTask;
+import jdk.jshell.TypePrinter.AnonymousTypeKind;
 
 /**
  * Compute information about an expression string, particularly its type name.
@@ -57,26 +74,75 @@
     final AnalyzeTask at;
     final CompilationUnitTree cu;
     final JShell state;
+    final boolean computeEnhancedInfo;
+    final boolean enhancedTypesAccessible;
     final Symtab syms;
     final Types types;
+    final Map<TypeSymbol, String> anon2Name = new HashMap<>();
 
-    private ExpressionToTypeInfo(AnalyzeTask at, CompilationUnitTree cu, JShell state) {
+    private ExpressionToTypeInfo(AnalyzeTask at, CompilationUnitTree cu, JShell state,
+                                 boolean computeEnhancedInfo, boolean enhancedTypesAccessible) {
         this.at = at;
         this.cu = cu;
         this.state = state;
+        this.computeEnhancedInfo = computeEnhancedInfo;
+        this.enhancedTypesAccessible = enhancedTypesAccessible;
         this.syms = Symtab.instance(at.context);
         this.types = Types.instance(at.context);
     }
 
     public static class ExpressionInfo {
         ExpressionTree tree;
+        boolean isPrimitiveType;
         String typeName;
         String accessibleTypeName;
+        /* In result of localVariableTypeForInitializer, the type that should be used
+         * as a declaration type of the field. This does not include intersection types,
+         * but does contain references to anonymous types converted to member types.
+         */
+        String declareTypeName;
+        /* In result of localVariableTypeForInitializer, the apparent/infered type of
+         * the variable. This includes intersection types, and references to anonymous
+         * types converted to member types.
+         */
         String fullTypeName;
-        List<String> parameterTypes;
-        String enclosingInstanceType;
-        boolean isClass;
+        /* In result of localVariableTypeForInitializer, the human readable type of
+         * the variable. This includes intersection types, and human readable descriptions
+         * of anonymous types.
+         */
+        String displayTypeName;
         boolean isNonVoid;
+        /* In result of localVariableTypeForInitializer, description of important anonymous
+         * classes.
+         */
+        List<AnonymousDescription> anonymousClasses = List.nil();
+
+        /* A description of an anonymous class. */
+        static class AnonymousDescription {
+            /* Parameter types of the invoked super constructor.*/
+            List<String> parameterTypes;
+            /* Type of the base/enclosing expression, if any.*/
+            String enclosingInstanceType;
+            /* The denotable name of the supertype.*/
+            String superTypeName;
+            /* The human-readable name of this class.*/
+            String declareTypeName;
+            /* If the supertype of this anonymous is a class. */
+            boolean isClass;
+            /* Variables captured by this anonymous class*/
+            List<VariableDesc> capturedVariables;
+
+            static class VariableDesc {
+                String type;
+                String name;
+
+                public VariableDesc(String type, String name) {
+                    this.type = type;
+                    this.name = name;
+                }
+
+            }
+        }
     }
 
     // return mechanism and other general structure from TreePath.getPath()
@@ -173,7 +239,7 @@
                 if (at.hasErrors() || cu == null) {
                     return null;
                 }
-                return new ExpressionToTypeInfo(at, cu, state).typeOfExpression();
+                return new ExpressionToTypeInfo(at, cu, state, false, false).typeOfExpression();
             });
         } catch (Exception ex) {
             return null;
@@ -187,7 +253,7 @@
      * @param state a JShell instance
      * @return type information
      */
-    public static ExpressionInfo localVariableTypeForInitializer(String code, JShell state) {
+    public static ExpressionInfo localVariableTypeForInitializer(String code, JShell state, boolean onlyAccessible) {
         if (code == null || code.isEmpty()) {
             return null;
         }
@@ -198,13 +264,37 @@
                 if (at.hasErrors() || cu == null) {
                     return null;
                 }
-                return new ExpressionToTypeInfo(at, cu, state).typeOfExpression();
+                return new ExpressionToTypeInfo(at, cu, state, true, onlyAccessible)
+                        .typeOfExpression();
             });
         } catch (Exception ex) {
             return null;
         }
     }
 
+    /**List (in a stable order) all NewClassTree instances under {@code from} that should be
+     * converted to member classes
+     *
+     * @param from tree to inspect
+     * @return NewClassTree instances that should be converted to member classes
+     */
+    public static List<NewClassTree> listAnonymousClassesToConvert(Tree from) {
+        ListBuffer<NewClassTree> classes = new ListBuffer<>();
+
+        new TreeScanner<Void, Void>() {
+            @Override
+            public Void visitNewClass(NewClassTree node, Void p) {
+                if (node.getClassBody() != null) {
+                    classes.append(node);
+                    return null;
+                }
+                return super.visitNewClass(node, p);
+            }
+        }.scan(from, null);
+
+        return classes.toList();
+    }
+
     private ExpressionInfo typeOfExpression() {
         return treeToInfo(findExpressionPath());
     }
@@ -256,23 +346,31 @@
      * @return the type, if it is accessible, otherwise a superclass or
      * interface which is
      */
-    private Type findAccessibleSupertype(Type type) {
+    private List<Type> findAccessibleSupertypes(Type type) {
+        List<Type> accessible = List.nil();
+        Type accessibleSuper = syms.objectType;
         // Iterate up the superclasses, see if any are accessible
         for (Type sup = type; !types.isSameType(sup, syms.objectType); sup = supertype(sup)) {
             if (isAccessible(sup)) {
-                return sup;
+                accessible = accessible.prepend(sup);
+                accessibleSuper = sup;
+                break;
             }
         }
-        // Failing superclasses, look through superclasses for accessible interfaces
-        for (Type sup = type; !types.isSameType(sup, syms.objectType); sup = supertype(sup)) {
+        // then look through superclasses for accessible interfaces
+        for (Type sup = type; !types.isSameType(sup, accessibleSuper); sup = supertype(sup)) {
             for (Type itf : types.interfaces(sup)) {
                 if (isAccessible(itf)) {
-                    return itf;
+                    accessible = accessible.prepend(itf);
                 }
             }
         }
-        // Punt, return Object which is the supertype of everything
-        return syms.objectType;
+        if (accessible.isEmpty()) {
+            // Punt, use Object which is the supertype of everything
+            accessible = accessible.prepend(syms.objectType);
+        }
+
+        return accessible.reverse();
     }
 
     private ExpressionInfo treeToInfo(TreePath tp) {
@@ -298,48 +396,125 @@
                             break;
                         default: {
                             ei.isNonVoid = true;
-                            ei.typeName = varTypeName(type, false);
-                            ei.accessibleTypeName = varTypeName(findAccessibleSupertype(type), false);
-                            ei.fullTypeName = varTypeName(type, true);
+                            ei.isPrimitiveType = type.isPrimitive();
+                            ei.typeName = varTypeName(type, false, AnonymousTypeKind.SUPER);
+                            List<Type> accessibleTypes = findAccessibleSupertypes(type);
+                            ei.accessibleTypeName =
+                                    varTypeName(accessibleTypes.head, false, AnonymousTypeKind.SUPER);
+                            if (computeEnhancedInfo) {
+                                Type accessibleType = accessibleTypes.size() == 1 ? accessibleTypes.head
+                                            : types.makeIntersectionType(accessibleTypes);
+                                ei.declareTypeName =
+                                        varTypeName(accessibleType, false, AnonymousTypeKind.DECLARE);
+                                ei.fullTypeName =
+                                        varTypeName(enhancedTypesAccessible ? accessibleType : type,
+                                                    true, AnonymousTypeKind.DECLARE);
+                                ei.displayTypeName =
+                                        varTypeName(type, true, AnonymousTypeKind.DISPLAY);
+                            }
                             break;
                         }
                     }
                 }
-                if (tree.getKind() == Tree.Kind.VARIABLE) {
+                if (tree.getKind() == Tree.Kind.VARIABLE && computeEnhancedInfo) {
                     Tree init = ((VariableTree) tree).getInitializer();
-                    if (init.getKind() == Tree.Kind.NEW_CLASS &&
-                        ((NewClassTree) init).getClassBody() != null) {
-                        NewClassTree nct = (NewClassTree) init;
-                        ClassTree clazz = nct.getClassBody();
-                        MethodTree constructor = (MethodTree) clazz.getMembers().get(0);
-                        ExpressionStatementTree superCallStatement =
-                                (ExpressionStatementTree) constructor.getBody().getStatements().get(0);
+                    for (NewClassTree node : listAnonymousClassesToConvert(init)) {
+                        Set<VariableElement> captured = capturedVariables(at,
+                                                                          tp.getCompilationUnit(),
+                                                                          node);
+                        JCClassDecl clazz = (JCClassDecl) node.getClassBody();
                         MethodInvocationTree superCall =
-                                (MethodInvocationTree) superCallStatement.getExpression();
-                        TreePath superCallPath =
-                                at.trees().getPath(tp.getCompilationUnit(), superCall.getMethodSelect());
+                                clazz.getMembers()
+                                     .stream()
+                                     .map(TreeInfo::firstConstructorCall)
+                                     .findAny()
+                                     .get();
+                        TreePath superCallPath
+                                = at.trees().
+                                        getPath(tp.getCompilationUnit(), superCall.
+                                                getMethodSelect());
                         Type constrType = pathToType(superCallPath);
-                        ei.parameterTypes = constrType.getParameterTypes()
-                                                      .stream()
-                                                      .map(t -> varTypeName(t, false))
-                                                      .collect(List.collector());
-                        if (nct.getEnclosingExpression() != null) {
-                            TreePath enclPath = new TreePath(tp, nct.getEnclosingExpression());
-                            ei.enclosingInstanceType = varTypeName(pathToType(enclPath), false);
+                        AnonymousDescription desc = new AnonymousDescription();
+                        desc.parameterTypes = constrType.getParameterTypes().
+                                stream().
+                                map(t -> varTypeName(t, false, AnonymousTypeKind.DECLARE)).
+                                collect(List.collector());
+                        if (node.getEnclosingExpression() != null) {
+                            TreePath enclPath = new TreePath(tp,
+                                                             node.getEnclosingExpression());
+                            desc.enclosingInstanceType = varTypeName(pathToType(enclPath),
+                                                                     false,
+                                                                     AnonymousTypeKind.DECLARE);
                         }
-                        ei.isClass = at.task.getTypes().directSupertypes(type).size() == 1;
+                        TreePath currentPath = at.trees()
+                                                 .getPath(tp.getCompilationUnit(),
+                                                          node);
+                        Type nodeType = pathToType(currentPath, node);
+                        desc.superTypeName = varTypeName(nodeType,
+                                                         false,
+                                                         AnonymousTypeKind.SUPER);
+                        desc.declareTypeName = varTypeName(nodeType,
+                                                           true, AnonymousTypeKind.DECLARE);
+                        desc.capturedVariables =
+                                captured.stream()
+                                        .map(ve -> new VariableDesc(varTypeName((Type) ve.asType(),
+                                                                                false,
+                                                                                AnonymousTypeKind.DECLARE),
+                                                                    ve.getSimpleName().toString()))
+                                        .collect(List.collector());
+
+                        desc.isClass = at.task.getTypes().directSupertypes(nodeType).size() == 1;
+                        ei.anonymousClasses = ei.anonymousClasses.prepend(desc);
                     }
+                    ei.anonymousClasses = ei.anonymousClasses.reverse();
                 }
                 return ei;
             }
         }
         return null;
     }
+    //where:
+        private static Set<VariableElement> capturedVariables(AnalyzeTask at,
+                                                              CompilationUnitTree topLevel,
+                                                              Tree tree) {
+            Set<VariableElement> capturedVars = new HashSet<>();
+            new TreeScanner<Void, Void>() {
+                Set<VariableElement> declaredLocalVars = new HashSet<>();
+                @Override
+                public Void visitVariable(VariableTree node, Void p) {
+                    TreePath currentPath = at.trees()
+                                             .getPath(topLevel, node);
+                    declaredLocalVars.add((VariableElement) at.trees().getElement(currentPath));
+                    return super.visitVariable(node, p);
+                }
 
-    private String varTypeName(Type type, boolean printIntersectionTypes) {
+                @Override
+                public Void visitIdentifier(IdentifierTree node, Void p) {
+                    TreePath currentPath = at.trees()
+                                             .getPath(topLevel, node);
+                    Element el = at.trees().getElement(currentPath);
+                    if (el != null &&
+                        LOCAL_VARIABLES.contains(el.getKind()) &&
+                        !declaredLocalVars.contains(el)) {
+                        capturedVars.add((VariableElement) el);
+                    }
+                    return super.visitIdentifier(node, p);
+                }
+            }.scan(tree, null);
+
+            return capturedVars;
+        }
+        private static final Set<ElementKind> LOCAL_VARIABLES =
+                EnumSet.of(ElementKind.EXCEPTION_PARAMETER, ElementKind.LOCAL_VARIABLE,
+                           ElementKind.PARAMETER, ElementKind.RESOURCE_VARIABLE);
+
+    private String varTypeName(Type type, boolean printIntersectionTypes, AnonymousTypeKind anonymousTypesKind) {
         try {
+            Function<TypeSymbol, String> anonymousClass2DeclareName =
+                    cs -> anon2Name.computeIfAbsent(cs, state.eval::computeDeclareName);
             TypePrinter tp = new TypePrinter(at.messages(),
-                    state.maps::fullClassNameAndPackageToClass, printIntersectionTypes);
+                    state.maps::fullClassNameAndPackageToClass, anonymousClass2DeclareName,
+                    printIntersectionTypes, anonymousTypesKind);
             List<Type> captures = types.captures(type);
             String res = tp.toString(types.upward(type, captures));
 
--- a/src/jdk.jshell/share/classes/jdk/jshell/TaskFactory.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/jdk.jshell/share/classes/jdk/jshell/TaskFactory.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 2018, 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
@@ -61,24 +61,33 @@
 import java.lang.Runtime.Version;
 import java.nio.CharBuffer;
 import java.util.function.BiFunction;
+import com.sun.source.tree.ClassTree;
 import com.sun.source.tree.Tree.Kind;
 import com.sun.source.util.TaskEvent;
 import com.sun.source.util.TaskListener;
 import com.sun.tools.javac.api.JavacTaskPool;
 import com.sun.tools.javac.code.ClassFinder;
 import com.sun.tools.javac.code.Kinds;
+import com.sun.tools.javac.code.Symbol;
 import com.sun.tools.javac.code.Symbol.ClassSymbol;
 import com.sun.tools.javac.code.Symbol.PackageSymbol;
+import com.sun.tools.javac.code.Symbol.TypeSymbol;
 import com.sun.tools.javac.code.Symbol.VarSymbol;
 import com.sun.tools.javac.code.Symtab;
+import com.sun.tools.javac.code.Type;
 import com.sun.tools.javac.comp.Attr;
+import com.sun.tools.javac.comp.AttrContext;
+import com.sun.tools.javac.comp.Enter;
+import com.sun.tools.javac.comp.Env;
+import com.sun.tools.javac.comp.Resolve;
 import com.sun.tools.javac.parser.Parser;
 import com.sun.tools.javac.parser.ParserFactory;
-import com.sun.tools.javac.tree.JCTree.JCClassDecl;
 import com.sun.tools.javac.tree.JCTree.JCCompilationUnit;
 import com.sun.tools.javac.tree.JCTree.JCExpression;
 import com.sun.tools.javac.tree.JCTree.JCTypeCast;
+import com.sun.tools.javac.tree.JCTree.JCVariableDecl;
 import com.sun.tools.javac.tree.JCTree.Tag;
+import com.sun.tools.javac.util.Context.Factory;
 import com.sun.tools.javac.util.Log;
 import com.sun.tools.javac.util.Log.DiscardDiagnosticHandler;
 import com.sun.tools.javac.util.Names;
@@ -197,6 +206,7 @@
                                          compilationUnits, task -> {
                  JavacTaskImpl jti = (JavacTaskImpl) task;
                  Context context = jti.getContext();
+                 DisableAccessibilityResolve.preRegister(context);
                  jti.addTaskListener(new TaskListenerImpl(context, state));
                  try {
                      return worker.withTask(creator.apply(jti, diagnostics));
@@ -578,10 +588,25 @@
         }
     }
 
+    /**The variable types inferred for "var"s may be non-denotable.
+     * jshell desugars these variables into fields, and fields must have
+     * a denotable type. So these fields are declared with some simpler denotable
+     * type, and the listener here enhances the types of the fields to be the full
+     * inferred types. This is mainly when the inferred type contains:
+     * -intersection types (e.g. <Z extends Runnable&CharSequence> Z get() {...} var z = get();)
+     * -types that are inaccessible at the given place
+     *
+     * This type enhancement does not need to do anything about anonymous classes, as these
+     * are desugared into member classes.
+     */
     private static final class TaskListenerImpl implements TaskListener {
 
         private final Context context;
         private final JShell state;
+        /* Keep the original (declaration) types of the fields that were enhanced.
+         * The declaration types need to be put back before writing the fields
+         * into classfiles.*/
+        private final Map<VarSymbol, Type> var2OriginalType = new HashMap<>();
 
         public TaskListenerImpl(Context context, JShell state) {
             this.context = context;
@@ -589,43 +614,85 @@
         }
 
         @Override
+        public void started(TaskEvent e) {
+            if (e.getKind() != TaskEvent.Kind.GENERATE)
+                return ;
+            //clear enhanced types in fields we are about to write to the classfiles:
+            for (Tree clazz : e.getCompilationUnit().getTypeDecls()) {
+                ClassTree ct = (ClassTree) clazz;
+
+                for (Tree member : ct.getMembers()) {
+                    if (member.getKind() != Tree.Kind.VARIABLE)
+                        continue;
+                    VarSymbol vsym = ((JCVariableDecl) member).sym;
+                    Type original = var2OriginalType.remove(vsym);
+                    if (original != null) {
+                        vsym.type = original;
+                    }
+                }
+            }
+        }
+
+        private boolean variablesSet = false;
+
+        @Override
         public void finished(TaskEvent e) {
-            if (e.getKind() != TaskEvent.Kind.ENTER)
+            if (e.getKind() != TaskEvent.Kind.ENTER || variablesSet)
                 return ;
             state.maps
                  .snippetList()
                  .stream()
                  .filter(s -> s.status() == Status.VALID)
                  .filter(s -> s.kind() == Snippet.Kind.VAR)
-                 .filter(s -> s.subKind() == Snippet.SubKind.VAR_DECLARATION_WITH_INITIALIZER_SUBKIND)
-                 .forEach(s -> setVariableType((JCCompilationUnit) e.getCompilationUnit(), (VarSnippet) s));
+                 .filter(s -> s.subKind() == Snippet.SubKind.VAR_DECLARATION_WITH_INITIALIZER_SUBKIND ||
+                              s.subKind() == Snippet.SubKind.TEMP_VAR_EXPRESSION_SUBKIND)
+                 .forEach(s -> setVariableType((VarSnippet) s));
+            variablesSet = true;
         }
 
-        private void setVariableType(JCCompilationUnit root, VarSnippet s) {
+        /* If the snippet contain enhanced types, enhance the type of
+         * the variable from snippet s to be the enhanced type.
+         */
+        private void setVariableType(VarSnippet s) {
+            String typeName = s.fullTypeName;
+
+            if (typeName == null)
+                return ;
+
             Symtab syms = Symtab.instance(context);
             Names names = Names.instance(context);
             Log log  = Log.instance(context);
             ParserFactory parserFactory = ParserFactory.instance(context);
             Attr attr = Attr.instance(context);
+            Enter enter = Enter.instance(context);
+            DisableAccessibilityResolve rs = (DisableAccessibilityResolve) Resolve.instance(context);
 
+            //find the variable:
             ClassSymbol clazz = syms.getClass(syms.unnamedModule, names.fromString(s.classFullName()));
             if (clazz == null || !clazz.isCompleted())
                 return;
             VarSymbol field = (VarSymbol) clazz.members().findFirst(names.fromString(s.name()), sym -> sym.kind == Kinds.Kind.VAR);
-            if (field != null) {
+
+            if (field != null && !var2OriginalType.containsKey(field)) {
+                //if it was not enhanced yet:
+                //ignore any errors:
                 JavaFileObject prev = log.useSource(null);
                 DiscardDiagnosticHandler h = new DiscardDiagnosticHandler(log);
                 try {
-                    String typeName = s.typeName();
+                    //parse the type as a cast, i.e. "(<typeName>) x". This is to support
+                    //intersection types:
                     CharBuffer buf = CharBuffer.wrap(("(" + typeName +")x\u0000").toCharArray(), 0, typeName.length() + 3);
                     Parser parser = parserFactory.newParser(buf, false, false, false);
                     JCExpression expr = parser.parseExpression();
                     if (expr.hasTag(Tag.TYPECAST)) {
+                        //if parsed OK, attribute and set the type:
+                        var2OriginalType.put(field, field.type);
+
                         JCTypeCast tree = (JCTypeCast) expr;
-                        if (tree.clazz.hasTag(Tag.TYPEINTERSECTION)) {
+                        rs.runWithoutAccessChecks(() -> {
                             field.type = attr.attribType(tree.clazz,
-                                                         ((JCClassDecl) root.getTypeDecls().head).sym);
-                        }
+                                                         enter.getEnvs().iterator().next().enclClass.sym);
+                        });
                     }
                 } finally {
                     log.popDiagnosticHandler(h);
@@ -635,4 +702,48 @@
         }
     }
 
+    private static final class DisableAccessibilityResolve extends Resolve {
+
+        public static void preRegister(Context context) {
+            if (context.get(Marker.class) == null) {
+                context.put(resolveKey, ((Factory<Resolve>) c -> new DisableAccessibilityResolve(c)));
+                context.put(Marker.class, new Marker());
+            }
+        }
+
+        private boolean noAccessChecks;
+
+        public DisableAccessibilityResolve(Context context) {
+            super(context);
+        }
+
+        /**Run the given Runnable with all access checks disabled.
+         *
+         * @param r Runnnable to run
+         */
+        public void runWithoutAccessChecks(Runnable r) {
+            boolean prevNoAccessCheckes = noAccessChecks;
+            try {
+                noAccessChecks = true;
+                r.run();
+            } finally {
+                noAccessChecks = prevNoAccessCheckes;
+            }
+        }
+
+        @Override
+        public boolean isAccessible(Env<AttrContext> env, TypeSymbol c, boolean checkInner) {
+            if (noAccessChecks) return true;
+            return super.isAccessible(env, c, checkInner);
+        }
+
+        @Override
+        public boolean isAccessible(Env<AttrContext> env, Type site, Symbol sym, boolean checkInner) {
+            if (noAccessChecks) return true;
+            return super.isAccessible(env, site, sym, checkInner);
+        }
+
+        private static final class Marker {}
+    }
+
 }
--- a/src/jdk.jshell/share/classes/jdk/jshell/TreeDissector.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/jdk.jshell/share/classes/jdk/jshell/TreeDissector.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 2018, 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
@@ -48,6 +48,7 @@
 import java.util.function.Predicate;
 import java.util.stream.Stream;
 import javax.lang.model.type.TypeMirror;
+import jdk.jshell.TypePrinter.AnonymousTypeKind;
 import jdk.jshell.Util.Pair;
 
 /**
@@ -227,7 +228,7 @@
         Type typeImpl = (Type) type;
         try {
             TypePrinter tp = new TypePrinter(at.messages(),
-                    state.maps::fullClassNameAndPackageToClass, true);
+                    state.maps::fullClassNameAndPackageToClass, true, AnonymousTypeKind.DISPLAY);
             return tp.toString(typeImpl);
         } catch (Exception ex) {
             return null;
--- a/src/jdk.jshell/share/classes/jdk/jshell/TypePrinter.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/jdk.jshell/share/classes/jdk/jshell/TypePrinter.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2018, 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
@@ -30,14 +30,17 @@
 import com.sun.tools.javac.code.Symbol;
 import com.sun.tools.javac.code.Symbol.ClassSymbol;
 import com.sun.tools.javac.code.Symbol.PackageSymbol;
+import com.sun.tools.javac.code.Symbol.TypeSymbol;
 import com.sun.tools.javac.code.Type;
 import com.sun.tools.javac.code.Type.ClassType;
 import com.sun.tools.javac.code.Type.IntersectionClassType;
 import com.sun.tools.javac.util.JavacMessages;
 import java.util.Locale;
 import java.util.function.BinaryOperator;
+import java.util.function.Function;
 import java.util.stream.Collectors;
 
+
 /**
  * Print types in source form.
  */
@@ -47,14 +50,44 @@
 
     private final JavacMessages messages;
     private final BinaryOperator<String> fullClassNameAndPackageToClass;
-    private final boolean printEnhancedTypes;
+    private final Function<TypeSymbol, String> anonymousToName;
+    private final boolean printIntersectionTypes;
+    private final AnonymousTypeKind anonymousTypesKind;
 
+    /**Create a TypePrinter.
+     *
+     * @param messages javac's messages
+     * @param fullClassNameAndPackageToClass convertor to convert full class names to
+     *                                       simple class names.
+     * @param printIntersectionTypes whether intersection types should be printed
+     * @param anonymousTypesKind how the anonymous types should be printed
+     */
     TypePrinter(JavacMessages messages,
                 BinaryOperator<String> fullClassNameAndPackageToClass,
-                boolean printEnhancedTypes) {
+                boolean printIntersectionTypes, AnonymousTypeKind anonymousTypesKind) {
+        this(messages, fullClassNameAndPackageToClass, cs -> cs.flatName().toString(),
+             printIntersectionTypes, anonymousTypesKind);
+    }
+
+    /**Create a TypePrinter.
+     *
+     * @param messages javac's messages
+     * @param fullClassNameAndPackageToClass convertor to convert full class names to
+     *                                       simple class names.
+     * @param anonymousToName convertor from anonymous classes to name that should be printed
+     *                        if anonymousTypesKind == AnonymousTypeKind.DECLARE
+     * @param printIntersectionTypes whether intersection types should be printed
+     * @param anonymousTypesKind how the anonymous types should be printed
+     */
+    TypePrinter(JavacMessages messages,
+                BinaryOperator<String> fullClassNameAndPackageToClass,
+                Function<TypeSymbol, String> anonymousToName,
+                boolean printIntersectionTypes, AnonymousTypeKind anonymousTypesKind) {
         this.messages = messages;
         this.fullClassNameAndPackageToClass = fullClassNameAndPackageToClass;
-        this.printEnhancedTypes = printEnhancedTypes;
+        this.anonymousToName = anonymousToName;
+        this.printIntersectionTypes = printIntersectionTypes;
+        this.anonymousTypesKind = anonymousTypesKind;
     }
 
     String toString(Type t) {
@@ -96,9 +129,9 @@
      */
     @Override
     protected String className(ClassType t, boolean longform, Locale locale) {
-        Symbol sym = t.tsym;
+        TypeSymbol sym = t.tsym;
         if (sym.name.length() == 0 && (sym.flags() & COMPOUND) != 0) {
-            if (printEnhancedTypes) {
+            if (printIntersectionTypes) {
                 return ((IntersectionClassType) t).getExplicitComponents()
                                                   .stream()
                                                   .map(i -> visit(i, locale))
@@ -107,18 +140,26 @@
                 return OBJECT;
             }
         } else if (sym.name.length() == 0) {
-            if (printEnhancedTypes) {
-                return t.tsym.flatName().toString().substring(t.tsym.outermostClass().flatName().length());
+            if (anonymousTypesKind == AnonymousTypeKind.DECLARE) {
+                return anonymousToName.apply(sym);
             }
             // Anonymous
             String s;
+            boolean isClass;
             ClassType norm = (ClassType) t.tsym.type;
             if (norm == null) {
                 s = OBJECT;
+                isClass = true;
             } else if (norm.interfaces_field != null && norm.interfaces_field.nonEmpty()) {
                 s = visit(norm.interfaces_field.head, locale);
+                isClass = false;
             } else {
                 s = visit(norm.supertype_field, locale);
+                isClass = true;
+            }
+            if (anonymousTypesKind == AnonymousTypeKind.DISPLAY) {
+                s = isClass ? "<anonymous class extending " + s + ">"
+                            : "<anonymous class implementing " + s + ">";
             }
             return s;
         } else if (longform) {
@@ -152,4 +193,14 @@
                 : s.fullname.toString();
     }
 
+    /** Specifies how the anonymous classes should be handled. */
+    public enum AnonymousTypeKind {
+        /* The anonymous class is printed as the name of its supertype. */
+        SUPER,
+        /* The anonymous class is printed as converted by the anonymousToName
+         * convertor. */
+        DECLARE,
+        /* The anonymous class is printed in a human readable form. */
+        DISPLAY;
+    }
 }
--- a/src/jdk.jshell/share/classes/jdk/jshell/Util.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/jdk.jshell/share/classes/jdk/jshell/Util.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 2018, 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
@@ -56,6 +56,11 @@
     static final String DOIT_METHOD_NAME = "do_it$";
 
     /**
+     * The prefix for all anonymous classes upgraded to member classes.
+     */
+    static final String JSHELL_ANONYMOUS = "$JShell$anonymous$";
+
+    /**
      * A pattern matching the full or simple class name of a wrapper class.
      */
     static final Pattern PREFIX_PATTERN = Pattern.compile(
--- a/src/jdk.jshell/share/classes/jdk/jshell/VarSnippet.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/jdk.jshell/share/classes/jdk/jshell/VarSnippet.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2018, 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
@@ -26,6 +26,8 @@
 package jdk.jshell;
 
 import java.util.Collection;
+import java.util.Set;
+import java.util.stream.Collectors;
 import jdk.jshell.Key.VarKey;
 
 /**
@@ -41,15 +43,30 @@
  */
 public class VarSnippet extends DeclarationSnippet {
 
+    /**A human readable type of the variable. May include intersection types
+     * and human readable description of anonymous classes.
+     */
     final String typeName;
 
+    /**The full type inferred for "var" variables. May include intersection types
+     * and inaccessible types. {@literal null} if enhancing the type is not necessary.
+     */
+    final String fullTypeName;
+
+    /**The anonymous class declared in the initializer of the "var" variable.
+     * These are automatically statically imported when the field is imported.
+     */
+    final Set<String> anonymousClasses;
+
      VarSnippet(VarKey key, String userSource, Wrap guts,
-            String name, SubKind subkind, String typeName,
-            Collection<String> declareReferences,
+            String name, SubKind subkind, String typeName, String fullTypeName,
+            Set<String> anonymousClasses, Collection<String> declareReferences,
             DiagList syntheticDiags) {
         super(key, userSource, guts, name, subkind, null, declareReferences,
                 null, syntheticDiags);
         this.typeName = typeName;
+        this.fullTypeName = fullTypeName;
+        this.anonymousClasses = anonymousClasses;
     }
 
     /**
@@ -59,4 +76,13 @@
     public String typeName() {
         return typeName;
     }
+
+    @Override
+    String importLine(JShell state) {
+        return "import static " + classFullName() + "." + name() + ";\n" +
+               anonymousClasses.stream()
+                               .map(c -> "import static " + classFullName() + "." + c + ";\n")
+                               .collect(Collectors.joining());
+    }
+
 }
--- a/src/jdk.jshell/share/classes/jdk/jshell/Wrap.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/jdk.jshell/share/classes/jdk/jshell/Wrap.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2018, 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
@@ -25,7 +25,9 @@
 
 package jdk.jshell;
 
+import java.util.ArrayList;
 import java.util.Arrays;
+import java.util.List;
 import static java.util.stream.Collectors.joining;
 import static jdk.jshell.Util.DOIT_METHOD_NAME;
 
@@ -66,37 +68,76 @@
         return "\n" + indent(n);
     }
 
-    /**
+    /**Create a stub of a compilable representation of a variable snippet.
+     * The variable is always represented by a field. If the variable
+     * in the snippet has an initializer, the field is initialized by
+     * calling the DOIT_METHOD_NAME method.
      *
-     * @param in
-     * @param rname
-     * @param rinit Initializer or null
-     * @param rdecl Type name and name
-     * @return
+     * In some cases, the real inferred type of the variable may be non-denotable
+     * (e.g. intersection types). The declared type of the field must always
+     * be denotable (i.e. such that it can be written into the classfile), but
+     * if the real type is potentially non-denotable, the {@code enhanced} parameter
+     * must be true.
+     *
+     * @param source the snippet's masked source code
+     * @param wtype variable's denotable type suitable for field declaration
+     * @param brackets any [] that should be appended to the type
+     * @param rname range in source that denotes the name of the
+     * @param winit Initializer or null
+     * @param enhanced if the real inferred type of the variable is potentially
+     *                 non-denotable, this must be true
+     * @return a Wrap that declares the given variable, potentially with
+     *         an initialization method
      */
     public static Wrap varWrap(String source, Wrap wtype, String brackets,
-                               Range rname, Wrap winit, Wrap anonDeclareWrap) {
+                               Range rname, Wrap winit, boolean enhanced,
+                               Wrap anonDeclareWrap) {
         RangeWrap wname = new RangeWrap(source, rname);
-        Wrap wVarDecl = new VarDeclareWrap(wtype, brackets, wname);
+        List<Object> components = new ArrayList<>();
+        components.add(new VarDeclareWrap(wtype, brackets, wname));
         Wrap wmeth;
 
         if (winit == null) {
             wmeth = new CompoundWrap(new NoWrap(" "), "   return null;\n");
         } else {
-        // int x = y
-            // int x_ = y; return x = x_;
-            // decl + "_ = " + init ; + "return " + name + "=" + name + "_ ;"
-            wmeth = new CompoundWrap(
-                    wtype, brackets + " ", wname, "_ =\n        ", winit, semi(winit),
-                    "        return ", wname, " = ", wname, "_;\n"
-            );
+            // int x = y
+            if (enhanced) {
+                // private static <Z> Z do_itAux() {
+                //     wtype x_ = y;
+                //     @SuppressWarnings("unchecked")
+                //     Z x__ = (Z) x_;
+                //     return x__;
+                // }
+                // in do_it method:
+                //return do_itAux();
+                Wrap waux = new CompoundWrap(
+                        "    private static <Z> Z ", DOIT_METHOD_NAME + "Aux", "() throws Throwable {\n",
+                        wtype, brackets + " ", wname, "_ =\n        ", winit, semi(winit),
+                        "        @SuppressWarnings(\"unchecked\") Z ", wname, "__ = (Z)", wname, "_;\n",
+                        "        return ", wname, "__;\n",
+                        "}"
+                );
+                components.add(waux);
+                wmeth = new CompoundWrap(
+                        "        return ", wname, " = ", DOIT_METHOD_NAME + "Aux", "();\n"
+                );
+            } else {
+                // int x_ = y; return x = x_;
+                // decl + "_ = " + init ; + "return " + name + "= " + name + "_ ;"
+                wmeth = new CompoundWrap(
+                        wtype, brackets + " ", wname, "_ =\n        ", winit, semi(winit),
+                        "        return ", wname, " = ", wname, "_;\n"
+                );
+            }
         }
-        Wrap wInitMeth = new DoitMethodWrap(wmeth);
-        return anonDeclareWrap != null ? new CompoundWrap(wVarDecl, wInitMeth, anonDeclareWrap)
-                                       : new CompoundWrap(wVarDecl, wInitMeth);
+        components.add(new DoitMethodWrap(wmeth));
+        if (anonDeclareWrap != null) {
+            components.add(anonDeclareWrap);
+        }
+        return new CompoundWrap(components.toArray());
     }
 
-    public static Wrap tempVarWrap(String source, String typename, String name) {
+    public static Wrap tempVarWrap(String source, String typename, String name, Wrap anonDeclareWrap) {
         RangeWrap winit = new NoWrap(source);
         // y
         // return $1 = y;
@@ -105,7 +146,8 @@
         Wrap wInitMeth = new DoitMethodWrap(wmeth);
 
         String varDecl = "    public static\n    " + typename + " " + name + ";\n";
-        return new CompoundWrap(varDecl, wInitMeth);
+        return anonDeclareWrap != null ? new CompoundWrap(varDecl, wInitMeth, anonDeclareWrap)
+                                       : new CompoundWrap(varDecl, wInitMeth);
     }
 
     public static Wrap simpleWrap(String source) {
--- a/src/jdk.management.agent/share/classes/sun/management/jmxremote/SingleEntryRegistry.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/jdk.management.agent/share/classes/sun/management/jmxremote/SingleEntryRegistry.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2017, 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
@@ -46,7 +46,7 @@
 public class SingleEntryRegistry extends RegistryImpl {
     SingleEntryRegistry(int port, String name, Remote object)
             throws RemoteException {
-        super(port);
+        super(port, null, null, SingleEntryRegistry::singleRegistryFilter);
         this.name = name;
         this.object = object;
     }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/jdk.naming.dns/share/classes/com/sun/jndi/dns/DNSDatagramSocketFactory.java	Fri Jan 19 09:32:10 2018 -0800
@@ -0,0 +1,246 @@
+/*
+ * Copyright (c) 2017, 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.jndi.dns;
+
+import java.io.IOException;
+import java.net.DatagramSocket;
+import java.net.ProtocolFamily;
+import java.net.SocketException;
+import java.net.InetSocketAddress;
+import java.nio.channels.DatagramChannel;
+import java.util.Objects;
+import java.util.Random;
+
+class DNSDatagramSocketFactory {
+    static final int DEVIATION = 3;
+    static final int THRESHOLD = 6;
+    static final int BIT_DEVIATION = 2;
+    static final int HISTORY = 32;
+    static final int MAX_RANDOM_TRIES = 5;
+    /**
+     * The dynamic allocation port range (aka ephemeral ports), as configured
+     * on the system. Use nested class for lazy evaluation.
+     */
+    static final class EphemeralPortRange {
+        private EphemeralPortRange() {}
+        static final int LOWER = sun.net.PortConfig.getLower();
+        static final int UPPER = sun.net.PortConfig.getUpper();
+        static final int RANGE = UPPER - LOWER + 1;
+    }
+
+    // Records a subset of max {@code capacity} previously used ports
+    static final class PortHistory {
+        final int capacity;
+        final int[] ports;
+        final Random random;
+        int index;
+        PortHistory(int capacity, Random random) {
+            this.random = random;
+            this.capacity = capacity;
+            this.ports = new int[capacity];
+        }
+        // returns true if the history contains the specified port.
+        public boolean contains(int port) {
+            int p = 0;
+            for (int i=0; i<capacity; i++) {
+                if ((p = ports[i]) == 0 || p == port) break;
+            }
+            return p == port;
+        }
+        // Adds the port to the history - doesn't check whether the port
+        // is already present. Always adds the port and always return true.
+        public boolean add(int port) {
+            if (ports[index] != 0) { // at max capacity
+                // remove one port at random and store the new port there
+                ports[random.nextInt(capacity)] = port;
+            } else { // there's a free slot
+                ports[index] = port;
+            }
+            if (++index == capacity) index = 0;
+            return true;
+        }
+        // Adds the port to the history if not already present.
+        // Return true if the port was added, false if the port was already
+        // present.
+        public boolean offer(int port) {
+            if (contains(port)) return false;
+            else return add(port);
+        }
+    }
+
+    int lastport = 0;
+    int suitablePortCount;
+    int unsuitablePortCount;
+    final ProtocolFamily family; // null (default) means dual stack
+    final int thresholdCount; // decision point
+    final int deviation;
+    final Random random;
+    final PortHistory history;
+
+    DNSDatagramSocketFactory() {
+        this(new Random());
+    }
+
+    DNSDatagramSocketFactory(Random random) {
+        this(Objects.requireNonNull(random), null, DEVIATION, THRESHOLD);
+    }
+    DNSDatagramSocketFactory(Random random,
+                             ProtocolFamily family,
+                             int deviation,
+                             int threshold) {
+        this.random = Objects.requireNonNull(random);
+        this.history = new PortHistory(HISTORY, random);
+        this.family = family;
+        this.deviation = Math.max(1, deviation);
+        this.thresholdCount = Math.max(2, threshold);
+    }
+
+    /**
+     * Opens a datagram socket listening to the wildcard address on a
+     * random port. If the underlying OS supports UDP port randomization
+     * out of the box (if binding a socket to port 0 binds it to a random
+     * port) then the underlying OS implementation is used. Otherwise, this
+     * method will allocate and bind a socket on a randomly selected ephemeral
+     * port in the dynamic range.
+     * @return A new DatagramSocket bound to a random port.
+     * @throws SocketException if the socket cannot be created.
+     */
+    public synchronized DatagramSocket open() throws SocketException {
+        int lastseen = lastport;
+        DatagramSocket s;
+
+        boolean thresholdCrossed = unsuitablePortCount > thresholdCount;
+        if (thresholdCrossed) {
+            // Underlying stack does not support random UDP port out of the box.
+            // Use our own algorithm to allocate a random UDP port
+            s = openRandom();
+            if (s != null) return s;
+
+            // couldn't allocate a random port: reset all counters and fall
+            // through.
+            unsuitablePortCount = 0; suitablePortCount = 0; lastseen = 0;
+        }
+
+        // Allocate an ephemeral port (port 0)
+        s = openDefault();
+        lastport = s.getLocalPort();
+        if (lastseen == 0) {
+            history.offer(lastport);
+            return s;
+        }
+
+        thresholdCrossed = suitablePortCount > thresholdCount;
+        boolean farEnough = Integer.bitCount(lastseen ^ lastport) > BIT_DEVIATION
+                            && Math.abs(lastport - lastseen) > deviation;
+        boolean recycled = history.contains(lastport);
+        boolean suitable = (thresholdCrossed || farEnough && !recycled);
+        if (suitable && !recycled) history.add(lastport);
+
+        if (suitable) {
+            if (!thresholdCrossed) {
+                suitablePortCount++;
+            } else if (!farEnough || recycled) {
+                unsuitablePortCount = 1;
+                suitablePortCount = thresholdCount/2;
+            }
+            // Either the underlying stack supports random UDP port allocation,
+            // or the new port is sufficiently distant from last port to make
+            // it look like it is. Let's use it.
+            return s;
+        }
+
+        // Undecided... the new port was too close. Let's allocate a random
+        // port using our own algorithm
+        assert !thresholdCrossed;
+        DatagramSocket ss = openRandom();
+        if (ss == null) return s;
+        unsuitablePortCount++;
+        s.close();
+        return ss;
+    }
+
+    private DatagramSocket openDefault() throws SocketException {
+        if (family != null) {
+            try {
+                DatagramChannel c = DatagramChannel.open(family);
+                try {
+                    DatagramSocket s = c.socket();
+                    s.bind(null);
+                    return s;
+                } catch (Throwable x) {
+                    c.close();
+                    throw x;
+                }
+            } catch (SocketException x) {
+                throw x;
+            } catch (IOException x) {
+                SocketException e = new SocketException(x.getMessage());
+                e.initCause(x);
+                throw e;
+            }
+        }
+        return new DatagramSocket();
+    }
+
+    synchronized boolean isUsingNativePortRandomization() {
+        return  unsuitablePortCount <= thresholdCount
+                && suitablePortCount > thresholdCount;
+    }
+
+    synchronized boolean isUsingJavaPortRandomization() {
+        return unsuitablePortCount > thresholdCount ;
+    }
+
+    synchronized boolean isUndecided() {
+        return !isUsingJavaPortRandomization()
+                && !isUsingNativePortRandomization();
+    }
+
+    private DatagramSocket openRandom() {
+        int maxtries = MAX_RANDOM_TRIES;
+        while (maxtries-- > 0) {
+            int port = EphemeralPortRange.LOWER
+                    + random.nextInt(EphemeralPortRange.RANGE);
+            try {
+                if (family != null) {
+                    DatagramChannel c = DatagramChannel.open(family);
+                    try {
+                        DatagramSocket s = c.socket();
+                        s.bind(new InetSocketAddress(port));
+                        return s;
+                    } catch (Throwable x) {
+                        c.close();
+                        throw x;
+                    }
+                }
+                return new DatagramSocket(port);
+            } catch (IOException x) {
+                // try again until maxtries == 0;
+            }
+        }
+        return null;
+    }
+
+}
--- a/src/jdk.naming.dns/share/classes/com/sun/jndi/dns/DnsClient.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/jdk.naming.dns/share/classes/com/sun/jndi/dns/DnsClient.java	Fri Jan 19 09:32:10 2018 -0800
@@ -85,7 +85,9 @@
     private int timeout;                // initial timeout on UDP queries in ms
     private int retries;                // number of UDP retries
 
-    private DatagramSocket udpSocket;
+    private final Object udpSocketLock = new Object();
+    private static final DNSDatagramSocketFactory factory =
+            new DNSDatagramSocketFactory(random);
 
     // Requests sent
     private Map<Integer, ResourceRecord> reqs;
@@ -105,14 +107,6 @@
             throws NamingException {
         this.timeout = timeout;
         this.retries = retries;
-        try {
-            udpSocket = new DatagramSocket();
-        } catch (java.net.SocketException e) {
-            NamingException ne = new ConfigurationException();
-            ne.setRootCause(e);
-            throw ne;
-        }
-
         this.servers = new InetAddress[servers.length];
         serverPorts = new int[servers.length];
 
@@ -142,6 +136,16 @@
         resps = Collections.synchronizedMap(new HashMap<Integer, byte[]>());
     }
 
+    DatagramSocket getDatagramSocket() throws NamingException {
+        try {
+            return factory.open();
+        } catch (java.net.SocketException e) {
+            NamingException ne = new ConfigurationException();
+            ne.setRootCause(e);
+            throw ne;
+        }
+    }
+
     @SuppressWarnings("deprecation")
     protected void finalize() {
         close();
@@ -151,7 +155,6 @@
     private Object queuesLock = new Object();
 
     public void close() {
-        udpSocket.close();
         synchronized (queuesLock) {
             reqs.clear();
             resps.clear();
@@ -393,43 +396,45 @@
 
         int minTimeout = 50; // msec after which there are no retries.
 
-        synchronized (udpSocket) {
-            DatagramPacket opkt = new DatagramPacket(
-                    pkt.getData(), pkt.length(), server, port);
-            DatagramPacket ipkt = new DatagramPacket(new byte[8000], 8000);
-            // Packets may only be sent to or received from this server address
-            udpSocket.connect(server, port);
-            int pktTimeout = (timeout * (1 << retry));
-            try {
-                udpSocket.send(opkt);
+        synchronized (udpSocketLock) {
+            try (DatagramSocket udpSocket = getDatagramSocket()) {
+                DatagramPacket opkt = new DatagramPacket(
+                        pkt.getData(), pkt.length(), server, port);
+                DatagramPacket ipkt = new DatagramPacket(new byte[8000], 8000);
+                // Packets may only be sent to or received from this server address
+                udpSocket.connect(server, port);
+                int pktTimeout = (timeout * (1 << retry));
+                try {
+                    udpSocket.send(opkt);
 
-                // timeout remaining after successive 'receive()'
-                int timeoutLeft = pktTimeout;
-                int cnt = 0;
-                do {
-                    if (debug) {
-                       cnt++;
-                        dprint("Trying RECEIVE(" +
-                                cnt + ") retry(" + (retry + 1) +
-                                ") for:" + xid  + "    sock-timeout:" +
-                                timeoutLeft + " ms.");
-                    }
-                    udpSocket.setSoTimeout(timeoutLeft);
-                    long start = System.currentTimeMillis();
-                    udpSocket.receive(ipkt);
-                    long end = System.currentTimeMillis();
+                    // timeout remaining after successive 'receive()'
+                    int timeoutLeft = pktTimeout;
+                    int cnt = 0;
+                    do {
+                        if (debug) {
+                           cnt++;
+                            dprint("Trying RECEIVE(" +
+                                    cnt + ") retry(" + (retry + 1) +
+                                    ") for:" + xid  + "    sock-timeout:" +
+                                    timeoutLeft + " ms.");
+                        }
+                        udpSocket.setSoTimeout(timeoutLeft);
+                        long start = System.currentTimeMillis();
+                        udpSocket.receive(ipkt);
+                        long end = System.currentTimeMillis();
 
-                    byte[] data = ipkt.getData();
-                    if (isMatchResponse(data, xid)) {
-                        return data;
-                    }
-                    timeoutLeft = pktTimeout - ((int) (end - start));
-                } while (timeoutLeft > minTimeout);
+                        byte[] data = ipkt.getData();
+                        if (isMatchResponse(data, xid)) {
+                            return data;
+                        }
+                        timeoutLeft = pktTimeout - ((int) (end - start));
+                    } while (timeoutLeft > minTimeout);
 
-            } finally {
-                udpSocket.disconnect();
+                } finally {
+                    udpSocket.disconnect();
+                }
+                return null; // no matching packet received within the timeout
             }
-            return null; // no matching packet received within the timeout
         }
     }
 
--- a/src/jdk.naming.dns/share/classes/com/sun/jndi/dns/ResourceRecord.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/jdk.naming.dns/share/classes/com/sun/jndi/dns/ResourceRecord.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2017, 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
@@ -355,8 +355,19 @@
                     pos += typeAndLen;
                 } else if ((typeAndLen & 0xC0) == 0xC0) { // name compression
                     ++level;
-                    endPos = pos + 2;
+                    // cater for the case where the name pointed to is itself
+                    // compressed: we don't want endPos to be reset by the second
+                    // compression level.
+                    int ppos = pos;
+                    if (endPos == -1) endPos = pos + 2;
                     pos = getUShort(pos) & 0x3FFF;
+                    if (debug) {
+                        dprint("decode: name compression at " + ppos
+                                + " -> " + pos + " endPos=" + endPos);
+                        assert endPos > 0;
+                        assert pos < ppos;
+                        assert pos >= Header.HEADER_SIZE;
+                    }
                 } else
                     throw new IOException("Invalid label type: " + typeAndLen);
             }
@@ -405,6 +416,11 @@
             }
         }
         // Unknown RR type/class
+        if (debug) {
+            dprint("Unknown RR type for RR data: " + rrtype + " rdlen=" + rdlen
+                   + ", pos=" + pos +", msglen=" + msg.length + ", remaining="
+                   + (msg.length-pos));
+        }
         byte[] rd = new byte[rdlen];
         System.arraycopy(msg, pos, rd, 0, rdlen);
         return rd;
@@ -613,4 +629,15 @@
 
         return sb.toString();
     }
+
+    //-------------------------------------------------------------------------
+
+    private static final boolean debug = false;
+
+    private static void dprint(String mess) {
+        if (debug) {
+            System.err.println("DNS: " + mess);
+        }
+    }
+
 }
--- a/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/CodeGenerator.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/CodeGenerator.java	Fri Jan 19 09:32:10 2018 -0800
@@ -2680,9 +2680,8 @@
             return false;
         }
 
-        if(isDeoptimizedExpression(lhs)) {
-            // This is actually related to "lhs.getType().isPrimitive()" above: any expression being deoptimized in
-            // the current chain of rest-of compilations used to have a type narrower than Object (so it was primitive).
+        if(containsOptimisticExpression(lhs)) {
+            // Any optimistic expression within lhs could be deoptimized and trigger a rest-of compilation.
             // We must not perform undefined check specialization for them, as then we'd violate the basic rule of
             // "Thou shalt not alter the stack shape between a deoptimized method and any of its (transitive) rest-ofs."
             return false;
@@ -2749,11 +2748,10 @@
             return false;
         }
 
-        if(isDeoptimizedExpression(lhs)) {
-            // This is actually related to "!lhs.getType().isObject()" above: any expression being deoptimized in
-            // the current chain of rest-of compilations used to have a type narrower than Object. We must not
-            // perform null check specialization for them, as then we'd no longer be loading aconst_null on stack
-            // and thus violate the basic rule of "Thou shalt not alter the stack shape between a deoptimized
+        if(containsOptimisticExpression(lhs)) {
+            // Any optimistic expression within lhs could be deoptimized and trigger a rest-of compilation.
+            // We must not perform null check specialization for them, as then we'd no longer be loading aconst_null
+            // on stack and thus violate the basic rule of "Thou shalt not alter the stack shape between a deoptimized
             // method and any of its (transitive) rest-ofs."
             // NOTE also that if we had a representation for well-known constants (e.g. null, 0, 1, -1, etc.) in
             // Label$Stack.localLoads then this wouldn't be an issue, as we would never (somewhat ridiculously)
@@ -2818,12 +2816,14 @@
     }
 
     /**
-     * Was this expression or any of its subexpressions deoptimized in the current recompilation chain of rest-of methods?
+     * Is this expression or any of its subexpressions optimistic? This includes formerly optimistic
+     * expressions that have been deoptimized in a subsequent compilation.
+     *
      * @param rootExpr the expression being tested
-     * @return true if the expression or any of its subexpressions was deoptimized in the current recompilation chain.
+     * @return true if the expression or any of its subexpressions is optimistic in the current compilation.
      */
-    private boolean isDeoptimizedExpression(final Expression rootExpr) {
-        if(!isRestOf()) {
+    private boolean containsOptimisticExpression(final Expression rootExpr) {
+        if(!useOptimisticTypes()) {
             return false;
         }
         return new Supplier<Boolean>() {
@@ -2839,7 +2839,7 @@
                     public boolean enterDefault(final Node node) {
                         if(!contains && node instanceof Optimistic) {
                             final int pp = ((Optimistic)node).getProgramPoint();
-                            contains = isValid(pp) && isContinuationEntryPoint(pp);
+                            contains = isValid(pp);
                         }
                         return !contains;
                     }
--- a/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/OptimisticTypesCalculator.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/OptimisticTypesCalculator.java	Fri Jan 19 09:32:10 2018 -0800
@@ -101,12 +101,13 @@
                     tagNeverOptimistic(binaryNode.rhs());
                 }
             }
-        } else if(binaryNode.isTokenType(TokenType.INSTANCEOF)) {
+        } else if(binaryNode.isTokenType(TokenType.INSTANCEOF)
+                || binaryNode.isTokenType(TokenType.EQ_STRICT)
+                || binaryNode.isTokenType(TokenType.NE_STRICT)) {
             tagNeverOptimistic(binaryNode.lhs());
             tagNeverOptimistic(binaryNode.rhs());
         }
-        // Don't enter comparison nodes, see JDK-8193567
-        return !binaryNode.isComparison();
+        return true;
     }
 
     @Override
--- a/src/jdk.security.auth/share/classes/com/sun/security/auth/module/LdapLoginModule.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/jdk.security.auth/share/classes/com/sun/security/auth/module/LdapLoginModule.java	Fri Jan 19 09:32:10 2018 -0800
@@ -737,7 +737,8 @@
 
         if (authFirst || authOnly) {
 
-            String id = replaceUsernameToken(identityMatcher, authcIdentity);
+            String id =
+                replaceUsernameToken(identityMatcher, authcIdentity, username);
 
             // Prepare to bind using user's username and password
             ldapEnvironment.put(Context.SECURITY_CREDENTIALS, password);
@@ -864,8 +865,13 @@
         }
 
         try {
-            NamingEnumeration<SearchResult> results = ctx.search("",
-                replaceUsernameToken(filterMatcher, userFilter), constraints);
+            // Sanitize username and substitute into LDAP filter
+            String canonicalUserFilter =
+                replaceUsernameToken(filterMatcher, userFilter,
+                    escapeUsernameChars());
+
+            NamingEnumeration<SearchResult> results =
+                ctx.search("", canonicalUserFilter, constraints);
 
             // Extract the distinguished name of the user's entry
             // (Use the first entry if more than one is returned)
@@ -913,12 +919,61 @@
     }
 
     /**
+     * Modify the supplied username to encode characters that must be escaped
+     * according to RFC 4515: LDAP: String Representation of Search Filters.
+     *
+     * The following characters are encoded as a backslash "\" (ASCII 0x5c)
+     * followed by the two hexadecimal digits representing the value of the
+     * escaped character:
+     *     '*' (ASCII 0x2a)
+     *     '(' (ASCII 0x28)
+     *     ')' (ASCII 0x29)
+     *     '\' (ASCII 0x5c)
+     *     '\0'(ASCII 0x00)
+     *
+     * @return the modified username with its characters escaped as needed
+     */
+    private String escapeUsernameChars() {
+        int len = username.length();
+        StringBuilder escapedUsername = new StringBuilder(len + 16);
+
+        for (int i = 0; i < len; i++) {
+            char c = username.charAt(i);
+            switch (c) {
+            case '*':
+                escapedUsername.append("\\\\2A");
+                break;
+            case '(':
+                escapedUsername.append("\\\\28");
+                break;
+            case ')':
+                escapedUsername.append("\\\\29");
+                break;
+            case '\\':
+                escapedUsername.append("\\\\5C");
+                break;
+            case '\0':
+                escapedUsername.append("\\\\00");
+                break;
+            default:
+                escapedUsername.append(c);
+            }
+        }
+
+        return escapedUsername.toString();
+    }
+
+
+    /**
      * Replace the username token
      *
+     * @param matcher the replacement pattern
      * @param string the target string
+     * @param username the supplied username
      * @return the modified string
      */
-    private String replaceUsernameToken(Matcher matcher, String string) {
+    private String replaceUsernameToken(Matcher matcher, String string,
+        String username) {
         return matcher != null ? matcher.replaceAll(username) : string;
     }
 
--- a/src/utils/LogCompilation/src/main/java/com/sun/hotspot/tools/compiler/CallSite.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/utils/LogCompilation/src/main/java/com/sun/hotspot/tools/compiler/CallSite.java	Fri Jan 19 09:32:10 2018 -0800
@@ -105,6 +105,11 @@
     private List<UncommonTrap> traps;
 
     /**
+     * The name of the intrinsic at this call site.
+     */
+    private String intrinsicName;
+
+    /**
      * Default constructor: used to create an instance that represents the top
      * scope of a compilation.
      */
@@ -179,6 +184,7 @@
         } else {
             stream.print("  @ " + getBci() + " " + m + " " + getReason());
         }
+        stream.print(getIntrinsicOrEmptyString());
         stream.printf(" (end time: %6.4f", getTimeStamp());
         if (getEndNodes() > 0) {
             stream.printf(" nodes: %d live: %d", getEndNodes(), getEndLiveNodes());
@@ -368,4 +374,19 @@
     public void setInlineId(long inlineId) {
         this.inlineId = inlineId;
     }
+
+    public String getIntrinsicName() {
+        return intrinsicName;
+    }
+
+    public void setIntrinsicName(String name) {
+        this.intrinsicName = name;
+    }
+
+    public String getIntrinsicOrEmptyString() {
+        if (intrinsicName != null) {
+            return " (intrinsic: " + getIntrinsicName() + ")";
+        }
+        return "";
+    }
 }
--- a/src/utils/LogCompilation/src/main/java/com/sun/hotspot/tools/compiler/LogParser.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/src/utils/LogCompilation/src/main/java/com/sun/hotspot/tools/compiler/LogParser.java	Fri Jan 19 09:32:10 2018 -0800
@@ -975,6 +975,12 @@
                 // track of it but don't add it to the list yet.
                 methodHandleSite = site;
             }
+        } else if (qname.equals("intrinsic")) {
+            String id = atts.getValue("id");
+            assert id != null : "intrinsic id is null";
+            CallSite cs = (site != null) ? site : scopes.peek();
+            assert cs != null : "no CallSite?";
+            cs.setIntrinsicName(id);
         } else if (qname.equals("regalloc")) {
             compile.setAttempts(Integer.parseInt(search(atts, "attempts")));
         } else if (qname.equals("inline_fail")) {
--- a/test/failure_handler/src/share/classes/jdk/test/failurehandler/jtreg/OS.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/test/failure_handler/src/share/classes/jdk/test/failurehandler/jtreg/OS.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2018, 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,7 +38,9 @@
     }
 
     private OS(String name) {
-        if (name.startsWith("Linux")) {
+        if (name.startsWith("AIX")) {
+            family = "aix";
+        } else if (name.startsWith("Linux")) {
             family = "linux";
         } else if (name.startsWith("Mac") || name.startsWith("Darwin")) {
             family = "mac";
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/hotspot/gtest/code/test_vtableStub.cpp	Fri Jan 19 09:32:10 2018 -0800
@@ -0,0 +1,52 @@
+/*
+ * Copyright (c) 2017, 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.
+ *
+ */
+
+#include "precompiled.hpp"
+#include "code/vtableStubs.hpp"
+#include "runtime/interfaceSupport.hpp"
+#include "unittest.hpp"
+
+TEST_VM(code, vtableStubs) {
+  // Should be in VM to use locks
+  ThreadInVMfromNative ThreadInVMfromNative(JavaThread::current());
+
+  VtableStubs::find_vtable_stub(0); // min vtable index
+  for (int i = 0; i < 15; i++) {
+    VtableStubs::find_vtable_stub((1 << i) - 1);
+    VtableStubs::find_vtable_stub((1 << i));
+  }
+  VtableStubs::find_vtable_stub((1 << 15) - 1); // max vtable index
+}
+
+TEST_VM(code, itableStubs) {
+  // Should be in VM to use locks
+  ThreadInVMfromNative ThreadInVMfromNative(JavaThread::current());
+
+  VtableStubs::find_itable_stub(0); // min itable index
+  for (int i = 0; i < 15; i++) {
+    VtableStubs::find_itable_stub((1 << i) - 1);
+    VtableStubs::find_itable_stub((1 << i));
+  }
+  VtableStubs::find_itable_stub((1 << 15) - 1); // max itable index
+}
--- a/test/hotspot/jtreg/Makefile	Thu Jan 18 11:22:28 2018 +0530
+++ b/test/hotspot/jtreg/Makefile	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 1995, 2016, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 1995, 2018, 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
@@ -66,13 +66,15 @@
   CONCURRENCY_FACTOR = 1
 endif
 
-# Concurrency based on min(cores / 2, 12)
-CONCURRENCY := $(shell awk 'BEGIN { printf "%.0f", $(NUM_CORES) / 2 * $(CONCURRENCY_FACTOR) }')
-ifeq ($(CONCURRENCY), 0)
-  CONCURRENCY := 1
-else ifeq ($(shell expr $(CONCURRENCY) \> 12), 1)
-  CONCURRENCY := 12
-endif
+# Concurrency based on min(cores / 2, 12) * CONCURRENCY_FACTOR
+CONCURRENCY := $(shell awk \
+  'BEGIN { \
+    c = $(NUM_CORES) / 2; \
+    if (c > 12) c = 12; \
+    c = c * $(CONCURRENCY_FACTOR); \
+    if (c < 1) c = 1; \
+    printf "%.0f", c; \
+  }')
 
 # Make sure MaxRAMPercentage is high enough to not cause OOM or swapping since we may end up with a lot of JVM's
 JTREG_BASIC_OPTIONS += -vmoption:-XX:MaxRAMPercentage=$(shell expr 25 / $(CONCURRENCY))
--- a/test/hotspot/jtreg/ProblemList.txt	Thu Jan 18 11:22:28 2018 +0530
+++ b/test/hotspot/jtreg/ProblemList.txt	Fri Jan 19 09:32:10 2018 -0800
@@ -71,6 +71,7 @@
 gc/stress/gclocker/TestGCLockerWithParallel.java 8180622 generic-all
 gc/stress/gclocker/TestGCLockerWithG1.java 8179226 generic-all
 gc/survivorAlignment/TestPromotionFromSurvivorToTenuredAfterMinorGC.java 8177765 generic-all
+gc/stress/TestJNIBlockFullGC/TestJNIBlockFullGC.java 8192647 generic-all
 
 #############################################################################
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/hotspot/jtreg/gc/g1/TestConcurrentSystemGC.java	Fri Jan 19 09:32:10 2018 -0800
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) 2018, 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 TestConcurrentSystemGC
+ * @bug 8195158
+ * @summary Test that a System.gc() with -XX:+ExplicitGCInvokesConcurrent
+ *          is *not* upgraded to STW full GC
+ * @key gc
+ * @requires vm.gc.G1
+ * @library /test/lib
+ * @modules java.base/jdk.internal.misc
+ *          java.management
+ * @run main/othervm -XX:+UseG1GC -XX:+ExplicitGCInvokesConcurrent -Xmx8m -Xms8m -XX:G1HeapRegionSize=1m TestConcurrentSystemGC
+ */
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class TestConcurrentSystemGC {
+    public static List<char[]> memory;
+    public static void main(String[] args) throws Exception {
+        memory = new ArrayList<>();
+        try {
+            while (true) {
+                memory.add(new char[1024 * 128]);
+                System.gc(); // should not trigger any assertions
+            }
+        } catch (OutOfMemoryError e) {
+            memory = null;
+            System.gc();
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/hotspot/jtreg/gc/stress/TestJNIBlockFullGC/TestJNIBlockFullGC.java	Fri Jan 19 09:32:10 2018 -0800
@@ -0,0 +1,181 @@
+/*
+ * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2017, SAP SE 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 TestJNIBlockFullGC
+ * @summary Check that in G1 a Full GC to reclaim space can not be blocked out by the GC locker.
+ * @key gc
+ * @requires vm.gc.G1
+ * @run main/othervm/native -Xmx64m -XX:+UseG1GC -Xlog:gc=info,gc+alloc=trace -XX:MaxGCPauseMillis=10 TestJNIBlockFullGC 10 10000 10000 10000 30000 10000 0.7
+ */
+
+import java.lang.ref.SoftReference;
+
+public class TestJNIBlockFullGC {
+
+    static {
+        System.loadLibrary("TestJNIBlockFullGC");
+    }
+
+    public static volatile Object tmp;
+
+    public static volatile boolean hadError = false;
+
+    private static native int TestCriticalArray0(int[] x);
+
+    public static class Node {
+        public SoftReference<Node> next;
+        long payload1;
+        long payload2;
+        long payload3;
+        long payload4;
+
+        public Node(int load) {
+            payload1 = payload2 = payload3 = payload4 = load;
+        }
+    }
+
+    public static void warmUp(long warmupEndTime, int size) {
+        // First let the GC assume most of our objects will die.
+        Node[] roots = new Node[size];
+
+        while (System.currentTimeMillis() < warmupEndTime) {
+            int index = (int) (Math.random() * roots.length);
+            roots[index] = new Node(1);
+        }
+
+        // Make sure the young generation is empty.
+        for (int i = 0; i < roots.length; ++i) {
+            roots[i] = null;
+        }
+    }
+
+    public static void runTest(long endTime, int size, double alive) {
+        final int length = 10000;
+        int[] array1 = new int[length];
+        for (int x = 1; x < length; x++) {
+            array1[x] = x;
+        }
+
+        Node[] roots = new Node[size];
+        try {
+            int index = 0;
+            roots[0] = new Node(0);
+
+            while (!hadError && (System.currentTimeMillis() < endTime)) {
+                int test_val1 = TestCriticalArray0(array1);
+
+                if (Math.random() > alive) {
+                    tmp = new Node(test_val1);
+                } else {
+                    index = (int) (Math.random() * roots.length);
+
+                    if (roots[index] != null) {
+                        Node node = new Node(test_val1);
+                        node.next = new SoftReference<Node>(roots[index]);
+                        roots[index] = node;
+                    } else {
+                        roots[index] = new Node(test_val1);
+                    }
+                }
+            }
+        } catch (OutOfMemoryError e) {
+            hadError = true;
+            e.printStackTrace();
+        }
+    }
+
+    private static void joinThreads(Thread[] threads) throws Exception {
+        for (int i = 0; i < threads.length; i++) {
+            try {
+                if (threads[i] != null) {
+                  threads[i].join();
+                }
+            } catch (InterruptedException e) {
+                e.printStackTrace();
+                throw e;
+            }
+        }
+    }
+
+    public static void main(String[] args) throws Exception {
+        if (args.length < 7){
+            System.out.println("Usage: java TestJNIBlockFullGC <warmupThreads> <warmup-time-in-millis> <warmup iterations> <threads> <time-in-millis> <iterations> <aliveFrac>");
+            System.exit(0);
+        }
+
+        int warmupThreads = Integer.parseInt(args[0]);
+        System.out.println("# Warmup Threads = " + warmupThreads);
+
+        int warmupDuration = Integer.parseInt(args[1]);
+        System.out.println("WarmUp Duration = " + warmupDuration);
+        int warmupIterations = Integer.parseInt(args[2]);
+        System.out.println("# Warmup Iterations = "+ warmupIterations);
+
+        int mainThreads = Integer.parseInt(args[3]);
+        System.out.println("# Main Threads = " + mainThreads);
+        int mainDuration = Integer.parseInt(args[4]);
+        System.out.println("Main Duration = " + mainDuration);
+        int mainIterations = Integer.parseInt(args[5]);
+        System.out.println("# Main Iterations = " + mainIterations);
+
+        double liveFrac = Double.parseDouble(args[6]);
+        System.out.println("Live Fraction = " + liveFrac);
+
+        Thread threads[] = new Thread[Math.max(warmupThreads, mainThreads)];
+
+        System.out.println("Start warm-up threads!");
+        long warmupStartTime = System.currentTimeMillis();
+        for (int i = 0; i < warmupThreads; i++) {
+            threads[i] = new Thread() {
+                public void run() {
+                    warmUp(warmupStartTime + warmupDuration, warmupIterations);
+                };
+            };
+            threads[i].start();
+        }
+
+        joinThreads(threads);
+
+        System.gc();
+        System.out.println("Keep alive a lot");
+
+        long startTime = System.currentTimeMillis();
+        for (int i = 0; i < mainThreads; i++) {
+            threads[i] = new Thread() {
+                public void run() {
+                    runTest(startTime + mainDuration, mainIterations, liveFrac);
+                };
+            };
+            threads[i].start();
+        }
+        System.out.println("All threads started");
+
+        joinThreads(threads);
+
+        if (hadError) {
+            throw new RuntimeException("Experienced an OoME during execution.");
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/hotspot/jtreg/gc/stress/TestJNIBlockFullGC/libTestJNIBlockFullGC.c	Fri Jan 19 09:32:10 2018 -0800
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2017, SAP SE 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.
+ */
+
+#include "jni.h"
+
+JNIEXPORT jint JNICALL
+Java_TestJNIBlockFullGC_TestCriticalArray0(JNIEnv *env, jclass jCls, jintArray jIn) {
+  jint *bufIn = NULL;
+  jint jInLen = (*env)->GetArrayLength(env, jIn);
+  jint result = 0;
+  jint i;
+
+  if (jInLen != 0) {
+    bufIn = (jint*)(*env)->GetPrimitiveArrayCritical(env, jIn, 0);
+  }
+
+  for (i = 0; i < jInLen; ++i) {
+    result += bufIn[i]; // result = sum of all array elements
+  }
+
+  if (bufIn != NULL) {
+    (*env)->ReleasePrimitiveArrayCritical(env, jIn, bufIn, 0);
+  }
+
+  return result;
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/hotspot/jtreg/gc/stress/TestReclaimStringsLeaksMemory.java	Fri Jan 19 09:32:10 2018 -0800
@@ -0,0 +1,103 @@
+/*
+ * Copyright (c) 2018, 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 TestReclaimStringsLeaksMemory
+ * @bug 8180048
+ * @summary Ensure that during a Full GC interned string memory is reclaimed completely.
+ * @requires vm.gc=="null"
+ * @requires !vm.debug
+ * @key gc
+ * @library /test/lib
+ * @modules java.base/jdk.internal.misc
+ * @run main/othervm TestReclaimStringsLeaksMemory
+ * @run main/othervm TestReclaimStringsLeaksMemory -XX:+UseSerialGC
+ * @run main/othervm TestReclaimStringsLeaksMemory -XX:+UseParallelGC
+ * @run main/othervm TestReclaimStringsLeaksMemory -XX:+UseParallelGC -XX:-UseParallelOldGC
+ * @run main/othervm TestReclaimStringsLeaksMemory -XX:+UseConcMarkSweepGC
+ * @run main/othervm TestReclaimStringsLeaksMemory -XX:+UseG1GC
+ */
+
+import java.util.Arrays;
+import java.util.ArrayList;
+import java.util.regex.Pattern;
+import java.util.regex.Matcher;
+
+import jdk.test.lib.Asserts;
+import jdk.test.lib.process.OutputAnalyzer;
+import jdk.test.lib.process.ProcessTools;
+
+public class TestReclaimStringsLeaksMemory {
+
+    // The amount of memory in kB reserved in the "Symbol" category that indicates a memory leak for
+    // this test.
+    public static final int ReservedThreshold = 70000;
+
+    public static void main(String[] args) throws Exception {
+        ArrayList<String> baseargs = new ArrayList(Arrays.asList( "-Xms256M",
+                                                                  "-Xmx256M",
+                                                                  "-Xlog:gc*",
+                                                                  "-XX:NativeMemoryTracking=summary",
+                                                                  "-XX:+UnlockDiagnosticVMOptions",
+                                                                  "-XX:+PrintNMTStatistics" ));
+        baseargs.addAll(Arrays.asList(args));
+        baseargs.add(GCTest.class.getName());
+        ProcessBuilder pb_default =
+            ProcessTools.createJavaProcessBuilder(baseargs.toArray(new String[] {}));
+        verifySymbolMemoryUsageNotTooHigh(new OutputAnalyzer(pb_default.start()));
+    }
+
+    private static void verifySymbolMemoryUsageNotTooHigh(OutputAnalyzer output) throws Exception {
+        String stdout = output.getStdout();
+        System.out.println(stdout);
+
+        Pattern p = Pattern.compile("Symbol \\(reserved=(\\d*)");
+        Matcher m = p.matcher(stdout);
+
+        if (!m.find()) {
+            throw new RuntimeException("Could not find Symbol memory usage in NMT output");
+        }
+
+        int reserved = Integer.parseInt(m.group(1));
+        Asserts.assertLT(reserved, ReservedThreshold, "Reserved memory size is " + reserved + "KB which is greater than or equal to " + ReservedThreshold + "KB indicating a memory leak");
+
+        output.shouldHaveExitValue(0);
+    }
+
+    static class GCTest {
+        public static final String BaseName = "SomeRandomBaseString";
+        public static volatile String lastString;
+
+        public static void main(String [] args) {
+            for (int iterations = 0; iterations < 20;) {
+                for (int i = 0; i < 1000000; i++) {
+                    lastString = (BaseName + i).intern();
+                }
+                if (++iterations % 5 == 0) {
+                   System.gc();
+                }
+            }
+        }
+    }
+}
+
--- a/test/hotspot/jtreg/runtime/6981737/Test6981737.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/test/hotspot/jtreg/runtime/6981737/Test6981737.java	Fri Jan 19 09:32:10 2018 -0800
@@ -41,8 +41,6 @@
         int major_version = Runtime.version().major();
         String vm_spec_version_re = Integer.toString(major_version);
 
-        verifyProperty("java.vendor", vendor_re);
-        verifyProperty("java.vm.vendor", vendor_re);
         verifyProperty("java.vm.specification.vendor", vendor_re);
         verifyProperty("java.specification.vendor", vendor_re);
         verifyProperty("java.vm.specification.version", vm_spec_version_re);
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/hotspot/jtreg/runtime/ErrorHandling/BadNativeStackInErrorHandlingTest.java	Fri Jan 19 09:32:10 2018 -0800
@@ -0,0 +1,104 @@
+/*
+ * Copyright (c) 2018, 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.
+ */
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.InputStreamReader;
+import java.util.regex.Pattern;
+
+import jdk.test.lib.Platform;
+import jdk.test.lib.process.OutputAnalyzer;
+import jdk.test.lib.process.ProcessTools;
+
+/*
+ * @test
+ * @bug 8194652
+ * @summary Printing native stack shows an "error occurred during error reporting".
+ * @modules java.base/jdk.internal.misc
+ * @library /test/lib
+ */
+
+// This test was adapted from SafeFetchInErrorHandlingTest.java.
+public class BadNativeStackInErrorHandlingTest {
+  public static void main(String[] args) throws Exception {
+    if (!Platform.isDebugBuild() || Platform.isZero()) {
+      return;
+    }
+
+    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
+        "-XX:+UnlockDiagnosticVMOptions",
+        "-Xmx100M",
+        "-XX:ErrorHandlerTest=14",
+        "-XX:-CreateCoredumpOnCrash",
+        "-version");
+
+    OutputAnalyzer output_detail = new OutputAnalyzer(pb.start());
+
+    // we should have crashed with a SIGSEGV
+    output_detail.shouldMatch("# A fatal error has been detected by the Java Runtime Environment:.*");
+    output_detail.shouldMatch("# +(?:SIGSEGV|EXCEPTION_ACCESS_VIOLATION).*");
+
+    // extract hs-err file
+    String hs_err_file = output_detail.firstMatch("# *(\\S*hs_err_pid\\d+\\.log)", 1);
+    if (hs_err_file == null) {
+        throw new RuntimeException("Did not find hs-err file in output.\n");
+    }
+
+    File f = new File(hs_err_file);
+    if (!f.exists()) {
+        throw new RuntimeException("hs-err file missing at " +
+                                   f.getAbsolutePath() + ".\n");
+    }
+
+    System.out.println("Found hs_err file. Scanning...");
+
+    FileInputStream fis = new FileInputStream(f);
+    BufferedReader br = new BufferedReader(new InputStreamReader(fis));
+    String line = null;
+
+    // The failing line looks like this:
+    // [error occurred during error reporting (printing native stack), id 0xb]
+    Pattern pattern =
+        Pattern.compile("\\[error occurred during error reporting \\(printing native stack\\), id .*\\]");
+
+    String lastLine = null;
+    while ((line = br.readLine()) != null) {
+        if (pattern.matcher(line).matches()) {
+            System.out.println("Found: " + line + ".");
+            throw new RuntimeException("hs-err file should not contain: '" +
+                                       pattern + "'");
+        }
+        lastLine = line;
+    }
+    br.close();
+
+    if (!lastLine.equals("END.")) {
+        throw new RuntimeException("hs-err file incomplete (missing END marker.)");
+    } else {
+        System.out.println("End marker found.");
+    }
+
+    System.out.println("OK.");
+  }
+}
--- a/test/hotspot/jtreg/runtime/NMT/PrintNMTStatistics.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/test/hotspot/jtreg/runtime/NMT/PrintNMTStatistics.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2018, 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
@@ -46,7 +46,6 @@
     OutputAnalyzer output_detail = new OutputAnalyzer(pb.start());
     output_detail.shouldContain("Virtual memory map:");
     output_detail.shouldContain("Details:");
-    output_detail.shouldNotContain("error");
     output_detail.shouldHaveExitValue(0);
 
     // Make sure memory reserved for Module processing is recorded.
@@ -62,7 +61,6 @@
     output_summary.shouldContain("Java Heap (reserved=");
     output_summary.shouldNotContain("Virtual memory map:");
     output_summary.shouldNotContain("Details:");
-    output_summary.shouldNotContain("error");
     output_summary.shouldHaveExitValue(0);
     }
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/hotspot/jtreg/runtime/RedefineTests/RedefineInterfaceCall.java	Fri Jan 19 09:32:10 2018 -0800
@@ -0,0 +1,83 @@
+/*
+ * Copyright (c) 2017, 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 8174962
+ * @summary Redefine class with interface method call
+ * @library /test/lib
+ * @modules java.base/jdk.internal.misc
+ * @modules java.compiler
+ *          java.instrument
+ *          jdk.jartool/sun.tools.jar
+ * @run main RedefineClassHelper
+ * @run main/othervm -javaagent:redefineagent.jar -Xlog:redefine+class+update*=trace RedefineInterfaceCall
+ */
+
+import static jdk.test.lib.Asserts.assertEquals;
+
+interface I1 { default int m() { return 0; } }
+interface I2 extends I1 {}
+
+public class RedefineInterfaceCall {
+
+    public static class C implements I2 {
+        public int test(I2 i) {
+            return i.m(); // invokeinterface cpCacheEntry
+        }
+    }
+
+    static String newI1 =
+      "interface I1 { default int m() { return 1; } }";
+
+    static String newC =
+        "public class RedefineInterfaceCall$C implements I2 { " +
+        "  public int test(I2 i) { " +
+        "    return i.m(); " +
+        "  } " +
+        "} ";
+
+    static int test(I2 i) {
+        return i.m(); // invokeinterface cpCacheEntry
+    }
+
+    public static void main(String[] args) throws Exception {
+        C c = new C();
+
+        assertEquals(test(c),   0);
+        assertEquals(c.test(c), 0);
+
+        RedefineClassHelper.redefineClass(C.class, newC);
+
+        assertEquals(c.test(c), 0);
+
+        RedefineClassHelper.redefineClass(I1.class, newI1);
+
+        assertEquals(test(c),   1);
+        assertEquals(c.test(c), 1);
+
+        RedefineClassHelper.redefineClass(C.class, newC);
+
+        assertEquals(c.test(c), 1);
+    }
+}
--- a/test/hotspot/jtreg/runtime/SharedArchiveFile/serviceability/transformRelatedClasses/TransformTestCommon.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/test/hotspot/jtreg/runtime/SharedArchiveFile/serviceability/transformRelatedClasses/TransformTestCommon.java	Fri Jan 19 09:32:10 2018 -0800
@@ -63,8 +63,8 @@
                                             String parent, String child)
         throws Exception {
 
-        String parentSharedMatch = parent + " source: shared objects file";
-        String childSharedMatch =  child +  " source: shared objects file";
+        String parentSharedMatch = " " + parent + " source: shared objects file";
+        String childSharedMatch =  " " + child +  " source: shared objects file";
 
         if (entry.isParentExpectedShared)
             out.shouldContain(parentSharedMatch);
--- a/test/hotspot/jtreg/runtime/appcds/DirClasspathTest.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/test/hotspot/jtreg/runtime/appcds/DirClasspathTest.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2017, 2018, 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,8 +33,13 @@
 import jdk.test.lib.Platform;
 import jdk.test.lib.process.OutputAnalyzer;
 import java.io.File;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.Arrays;
 
 public class DirClasspathTest {
+    private static final int MAX_PATH = 260;
+
     public static void main(String[] args) throws Exception {
         File dir = new File(System.getProperty("user.dir"));
         File emptydir = new File(dir, "emptydir");
@@ -42,15 +47,36 @@
 
         // Empty dir in -cp: should be OK
         OutputAnalyzer output;
-        if (!Platform.isWindows()) {
-            // This block fails on Windows because of JDK-8192927
-            output = TestCommon.dump(emptydir.getPath(), TestCommon.list("DoesntMatter"), "-Xlog:class+path=info");
-            TestCommon.checkDump(output);
+        String classList[] = {"java/lang/Object"};
+        output = TestCommon.dump(emptydir.getPath(), classList, "-Xlog:class+path=info");
+        TestCommon.checkDump(output);
+
+        // Long path to empty dir in -cp: should be OK
+        Path classDir = Paths.get(System.getProperty("test.classes"));
+        Path destDir = classDir;
+        int subDirLen = MAX_PATH - classDir.toString().length() - 2;
+        if (subDirLen > 0) {
+            char[] chars = new char[subDirLen];
+            Arrays.fill(chars, 'x');
+            String subPath = new String(chars);
+            destDir = Paths.get(System.getProperty("test.classes"), subPath);
         }
+        File longDir = destDir.toFile();
+        longDir.mkdir();
+        File subDir = new File(longDir, "subdir");
+        subDir.mkdir();
+        output = TestCommon.dump(subDir.getPath(), classList, "-Xlog:class+path=info");
+        TestCommon.checkDump(output);
 
         // Non-empty dir in -cp: should fail
         // <dir> is not empty because it has at least one subdirectory, i.e., <emptydir>
-        output = TestCommon.dump(dir.getPath(), TestCommon.list("DoesntMatter"), "-Xlog:class+path=info");
+        output = TestCommon.dump(dir.getPath(), classList, "-Xlog:class+path=info");
+        output.shouldNotHaveExitValue(0);
+        output.shouldContain("CDS allows only empty directories in archived classpaths");
+
+        // Long path to non-empty dir in -cp: should fail
+        // <dir> is not empty because it has at least one subdirectory, i.e., <emptydir>
+        output = TestCommon.dump(longDir.getPath(), classList, "-Xlog:class+path=info");
         output.shouldNotHaveExitValue(0);
         output.shouldContain("CDS allows only empty directories in archived classpaths");
     }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/hotspot/jtreg/serviceability/sa/ClhsdbThread.java	Fri Jan 19 09:32:10 2018 -0800
@@ -0,0 +1,118 @@
+/*
+ * Copyright (c) 2018, 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.
+ */
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import jdk.test.lib.apps.LingeredApp;
+
+/*
+ * @test
+ * @bug 8193352
+ * @summary Test clhsdb 'thread' and 'threads' commands
+ * @library /test/lib
+ * @run main/othervm ClhsdbThread
+ */
+
+public class ClhsdbThread {
+
+    public static void main(String[] args) throws Exception {
+        System.out.println("Starting ClhsdbThread test");
+
+        LingeredApp theApp = null;
+        try {
+            ClhsdbLauncher test = new ClhsdbLauncher();
+            theApp = LingeredApp.startApp();
+            System.out.println("Started LingeredApp with pid " + theApp.getPid());
+
+            List<String> cmds = List.of("thread", "thread -a", "threads");
+
+            Map<String, List<String>> expStrMap = new HashMap<>();
+            // Check for the presence of the usage string
+            expStrMap.put("thread", List.of( "Usage: thread { -a | id }"));
+            expStrMap.put("thread -a", List.of(
+                "State: BLOCKED",
+                "Stack in use by Java",
+                "Base of Stack",
+                "Last_Java_SP:",
+                "Address"));
+            expStrMap.put("threads", List.of(
+                "Finalizer",
+                "Signal Dispatcher",
+                "Common-Cleaner",
+                "Stack in use by Java:",
+                "State:",
+                "Base of Stack:",
+                "main"));
+            Map<String, List<String>> unExpStrMap = new HashMap<>();
+            unExpStrMap.put(
+                "thread -a",
+                List.of("Couldn't find thread -a"));
+
+            String consolidatedOutput = test.run(
+                theApp.getPid(),
+                cmds,
+                expStrMap,
+                unExpStrMap);
+
+            if (consolidatedOutput == null) {
+                // Output could be null due to attach permission issues.
+                System.out.println(
+                    "Output is empty. Probably due to attach permission issues.");
+                LingeredApp.stopApp(theApp);
+                return;
+            }
+
+            // Test the thread <id> command now. Obtain <id> from the
+            // output of the previous 'threads' command. The word before
+            // the token 'Finalizer' should denote the thread id of the
+            // 'Finalizer' thread.
+
+            String[] snippets = consolidatedOutput.split("Finalizer");
+            String[] wordTokens = snippets[0].split(" ");
+            String threadIdObtained = wordTokens[wordTokens.length - 1];
+
+            // Weed out newlines and blurb before that.
+            if (threadIdObtained.contains("\n")) {
+                String[] threadIdTokens = threadIdObtained.split("\n");
+                threadIdObtained = threadIdTokens[threadIdTokens.length - 1];
+            }
+
+            expStrMap = new HashMap<>();
+            System.out.println("Thread Id obtained is: " + threadIdObtained);
+
+            String cmd = "thread " + threadIdObtained;
+            expStrMap.put(cmd, List.of(
+                "Base of Stack:",
+                "State:",
+                "Last_Java_SP"));
+            cmds = List.of(cmd);
+            test.run(theApp.getPid(), cmds, expStrMap, null);
+        } catch (Exception ex) {
+            throw new RuntimeException("Test ERROR " + ex, ex);
+        } finally {
+            LingeredApp.stopApp(theApp);
+        }
+        System.out.println("Test PASSED");
+    }
+}
--- a/test/jaxp/javax/xml/jaxp/unittest/common/Bug6941169Test.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/test/jaxp/javax/xml/jaxp/unittest/common/Bug6941169Test.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 2017, 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
@@ -364,6 +364,14 @@
 
     @Test
     public void testXPath_DOM_withServiceMech() {
+        /**
+         * This is in conflict with the test testXPath_DOM_withSM where the system
+         * default parser is used when the security manager is present. The test
+         * is therefore skipped when the security manager is present.
+         */
+        if (System.getSecurityManager() != null) {
+            return;
+        }
         final String XPATH_EXPRESSION = "/fooTest";
         System.out.println("Evaluate DOM Source;  Service mechnism is on by default;  It would try to use MyDOMFactoryImpl:");
         InputStream input = getClass().getResourceAsStream("Bug6941169.xml");
--- a/test/jdk/ProblemList.txt	Thu Jan 18 11:22:28 2018 +0530
+++ b/test/jdk/ProblemList.txt	Fri Jan 19 09:32:10 2018 -0800
@@ -254,7 +254,8 @@
 # jdk_security
 
 sun/security/pkcs11/ec/TestKeyFactory.java                      8026976 generic-all
-sun/security/pkcs11/KeyStore/SecretKeysBasic.sh                 8186098 linux-all
+sun/security/pkcs11/Secmod/AddTrustedCert.java                  8180837 generic-all
+sun/security/pkcs11/tls/TestKeyMaterial.java                    8180837 generic-all
 
 sun/security/tools/keytool/ListKeychainStore.sh                 8156889 macosx-all
 
--- a/test/jdk/com/sun/crypto/provider/KeyAgreement/DHGenSecretKey.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/test/jdk/com/sun/crypto/provider/KeyAgreement/DHGenSecretKey.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,6 +27,7 @@
  * @summary Verify that DHKeyAgreement can generate secret key
  * objects for AES algorithm
  * @author Valerie Peng
+ * @run main/othervm -Djdk.crypto.KeyAgreement.legacyKDF=true DHGenSecretKey
  */
 import java.security.*;
 import java.security.interfaces.*;
--- a/test/jdk/com/sun/crypto/provider/KeyAgreement/DHKeyAgreement2.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/test/jdk/com/sun/crypto/provider/KeyAgreement/DHKeyAgreement2.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, 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
@@ -26,6 +26,7 @@
  * @bug 7146728
  * @summary DHKeyAgreement2
  * @author Jan Luehe
+ * @run main/othervm -Djdk.crypto.KeyAgreement.legacyKDF=true DHKeyAgreement2
  */
 
 import java.io.*;
--- a/test/jdk/com/sun/crypto/provider/KeyAgreement/SameDHKeyStressTest.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/test/jdk/com/sun/crypto/provider/KeyAgreement/SameDHKeyStressTest.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2017, 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
@@ -26,7 +26,7 @@
  * @bug 8048819
  * @summary This test stressful verifies the assertion of "The secret keys generated
  * by all involved parties should be the same." for javax.crypto.KeyAgreement
- * @run main SameDHKeyStressTest
+ * @run main/othervm -Djdk.crypto.KeyAgreement.legacyKDF=true SameDHKeyStressTest
  */
 import java.security.AlgorithmParameterGenerator;
 import java.security.InvalidAlgorithmParameterException;
--- a/test/jdk/java/awt/FontClass/CreateFont/fileaccess/TestFontFile.sh	Thu Jan 18 11:22:28 2018 +0530
+++ b/test/jdk/java/awt/FontClass/CreateFont/fileaccess/TestFontFile.sh	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2015, 2018, 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
@@ -46,7 +46,7 @@
 # set platform-dependent variables
 OS=`uname -s`
 case "$OS" in
-  SunOS | Linux | Darwin )
+  AIX | Darwin | Linux | SunOS )
     NULL=/dev/null
     PS=":"
     FS="/"
--- a/test/jdk/java/awt/JAWT/JAWT.sh	Thu Jan 18 11:22:28 2018 +0530
+++ b/test/jdk/java/awt/JAWT/JAWT.sh	Fri Jan 19 09:32:10 2018 -0800
@@ -1,6 +1,6 @@
 #!/bin/sh
 
-# Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2012, 2018, 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
@@ -62,6 +62,10 @@
 	MAKE="make"
 	LD_LIBRARY_PATH="."
     ;;
+  AIX )
+      echo "Test passed. Not supported on AIX."
+      exit 0
+    ;;
   SunOS )
     NULL=/dev/null
     PS=":"
--- a/test/jdk/java/awt/Toolkit/AutoShutdown/EventQueuePush/EventQueuePushAutoshutdown.sh	Thu Jan 18 11:22:28 2018 +0530
+++ b/test/jdk/java/awt/Toolkit/AutoShutdown/EventQueuePush/EventQueuePushAutoshutdown.sh	Fri Jan 19 09:32:10 2018 -0800
@@ -1,7 +1,7 @@
 #!/bin/ksh -p
 
 #
-# Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2015, 2018, 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
@@ -60,7 +60,7 @@
 # The beginning of the script proper
 OS=`uname -s`
 case "$OS" in
-   SunOS | Linux | Darwin | CYGWIN* )
+   AIX | CYGWIN* | Darwin | Linux | SunOS )
       FILESEP="/"
       ;;
 
--- a/test/jdk/java/awt/Toolkit/Headless/WrappedToolkitTest/WrappedToolkitTest.sh	Thu Jan 18 11:22:28 2018 +0530
+++ b/test/jdk/java/awt/Toolkit/Headless/WrappedToolkitTest/WrappedToolkitTest.sh	Fri Jan 19 09:32:10 2018 -0800
@@ -1,7 +1,7 @@
 #!/bin/ksh -p
 
 #
-# Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2012, 2018, 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
@@ -59,7 +59,7 @@
 # Checking for proper OS
 OS=`uname -s`
 case "$OS" in
-   SunOS | Linux | Darwin | CYGWIN* )
+   AIX | CYGWIN* | Darwin | Linux | SunOS )
       FILESEP="/"
       ;;
     
@@ -172,7 +172,7 @@
     fi
     ;;
 
-  SunOS | Linux )
+  AIX | Linux | SunOS )
     ${TESTJAVA}/bin/java ${TESTVMOPTS} -Djava.awt.headless=true \
                          --add-opens java.desktop/sun.awt=ALL-UNNAMED \
                          --add-opens java.desktop/sun.awt.X11=ALL-UNNAMED ${CP} \
--- a/test/jdk/java/lang/Runtime/Version/Basic.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/test/jdk/java/lang/Runtime/Version/Basic.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -24,7 +24,7 @@
 /*
  * @test
  * @summary Unit test for java.lang.Runtime.Version
- * @bug 8072379 8144062 8161236 8160956
+ * @bug 8072379 8144062 8161236 8160956 8194879
  */
 
 import java.lang.Runtime.Version;
@@ -115,6 +115,7 @@
         tryCatch("9-pre+-opt", IAE);
         tryCatch("1.4142+-",   IAE);
         tryCatch("2.9979+-%",  IAE);
+        tryCatch("10--ea",     IAE);
 
         //// Test for Runtime.version()
         testVersion();
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/java/lang/invoke/FilterArgumentsTest.java	Fri Jan 19 09:32:10 2018 -0800
@@ -0,0 +1,132 @@
+/*
+ * Copyright (c) 2018, 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 8194554
+ * @run testng/othervm test.java.lang.invoke.FilterArgumentsTest
+ */
+
+package test.java.lang.invoke;
+
+import java.lang.invoke.MethodHandle;
+import java.lang.invoke.MethodHandles;
+import java.util.ArrayList;
+import java.util.List;
+
+import static java.lang.invoke.MethodHandles.*;
+import static java.lang.invoke.MethodType.methodType;
+
+import org.testng.annotations.*;
+import static org.testng.Assert.*;
+
+public class FilterArgumentsTest {
+
+    @Test
+    public static void testFilterA_B_C() throws Throwable {
+        FilterTest test = new FilterTest(
+            filterArguments(MH_TEST, 0, MH_FILTER_A, MH_FILTER_B, MH_FILTER_C));
+        test.run(List.of("A", "B", "C"));
+    }
+
+    @Test
+    public static void testFilterA_B() throws Throwable {
+        FilterTest test = new FilterTest(
+            filterArguments(MH_TEST, 0, MH_FILTER_A, MH_FILTER_B));
+        test.run(List.of("A", "B"));
+    }
+
+    @Test
+    public static void testFilterB_C() throws Throwable {
+        FilterTest test = new FilterTest(
+            filterArguments(MH_TEST, 1, MH_FILTER_B, MH_FILTER_C));
+        test.run(List.of("B", "C"));
+    }
+
+    @Test
+    public static void testFilterB() throws Throwable {
+        FilterTest test = new FilterTest(filterArguments(MH_TEST, 1, MH_FILTER_B));
+        test.run(List.of("B"));
+    }
+
+    @Test
+    public static void testFilterC() throws Throwable {
+        FilterTest test = new FilterTest(filterArguments(MH_TEST, 2, MH_FILTER_C));
+        test.run(List.of("C"));
+    }
+
+    static class FilterTest {
+        static List<String> filters = new ArrayList<>();
+
+        final MethodHandle mh;
+        FilterTest(MethodHandle mh) {
+            this.mh = mh;
+        }
+
+        void run(List<String> expected) throws Throwable {
+            filters.clear();
+            assertEquals("x-0-z", (String)mh.invokeExact("x", 0, 'z'));
+            assertEquals(expected, filters);
+        }
+
+        static String filterA(String s) {
+            filters.add("A");
+            return s;
+        }
+
+        static int filterB(int value) {
+            filters.add("B");
+            return value;
+        }
+
+        static char filterC(char c) {
+            filters.add("C");
+            return c;
+        }
+
+        static String test(String s, int i, char c) {
+            return s + "-" + i + "-" + c;
+        }
+    }
+
+    static final MethodHandle MH_TEST;
+    static final MethodHandle MH_FILTER_A;
+    static final MethodHandle MH_FILTER_B;
+    static final MethodHandle MH_FILTER_C;
+    static final Lookup LOOKUP = MethodHandles.lookup();
+
+    static {
+        try {
+            MH_TEST = LOOKUP.findStatic(FilterTest.class, "test",
+                methodType(String.class, String.class, int.class, char.class));
+            MH_FILTER_A = LOOKUP.findStatic(FilterTest.class, "filterA",
+                methodType(String.class, String.class));
+            MH_FILTER_B = LOOKUP.findStatic(FilterTest.class, "filterB",
+                methodType(int.class, int.class));
+            MH_FILTER_C = LOOKUP.findStatic(FilterTest.class, "filterC",
+                methodType(char.class, char.class));
+        } catch (Exception e) {
+            throw new RuntimeException(e);
+        }
+    }
+}
--- a/test/jdk/java/rmi/testlibrary/RMID.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/test/jdk/java/rmi/testlibrary/RMID.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -44,11 +44,12 @@
     private static final long TIMEOUT_DESTROY_MS  = 10_000L;
     private static final long STARTTIME_MS        = 15_000L;
     private static final long POLLTIME_MS         = 100L;
+    private static final long TIMEOUT_BASE        = 240_000L;
 
     // when restart rmid, it may take more time than usual because of
     // "port in use" by a possible interloper (check JDK-8168975),
-    // so need to set a longer timeout for restart.
-    private static long restartTimeout;
+    // so need to set a longer timeout than STARTTIME_MS for restart.
+    private static final long RESTART_TIMEOUT = (long)(TIMEOUT_BASE * 0.9);
     // Same reason to inheritedChannel in RMIDSelectorProvider.
     // Put it here rather than in RMIDSelectorProvider to adjust
     // both timeout values together.
@@ -264,8 +265,7 @@
     {
         super(classname, options, args, out, err);
         this.port = port;
-        long waitTime = (long)(240_000 * TestLibrary.getTimeoutFactor());
-        restartTimeout = (long)(waitTime * 0.9);
+        long waitTime = (long)(TIMEOUT_BASE * TestLibrary.getTimeoutFactor());
         inheritedChannelTimeout = (long)(waitTime * 0.8);
     }
 
@@ -406,7 +406,7 @@
         options = makeOptions(port, true, true);
         args = makeArgs();
 
-        start(restartTimeout);
+        start(RESTART_TIMEOUT);
     }
 
     /**
--- a/test/jdk/java/rmi/testlibrary/TestLibrary.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/test/jdk/java/rmi/testlibrary/TestLibrary.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2018, 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
@@ -186,9 +186,7 @@
      * Maximum timeout (before multipliers are applied) is one hour.
      */
     public static long computeDeadline(long timestamp, long timeout) {
-        final long MAX_TIMEOUT_MS = 3_600_000L;
-
-        if (timeout < 0L || timeout > MAX_TIMEOUT_MS) {
+        if (timeout < 0L) {
             throw new IllegalArgumentException("timeout " + timeout + "ms out of range");
         }
 
--- a/test/jdk/java/util/stream/test/org/openjdk/tests/java/util/stream/FlatMapOpTest.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/test/jdk/java/util/stream/test/org/openjdk/tests/java/util/stream/FlatMapOpTest.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -24,7 +24,7 @@
 /*
  * @test
  * @summary flat-map operations
- * @bug 8044047 8076458
+ * @bug 8044047 8076458 8075939
  */
 
 package org.openjdk.tests.java.util.stream;
@@ -54,6 +54,7 @@
 @Test
 public class FlatMapOpTest extends OpTestCase {
 
+    @Test
     public void testNullMapper() {
         checkNPE(() -> Stream.of(1).flatMap(null));
         checkNPE(() -> IntStream.of(1).flatMap(null));
@@ -64,6 +65,7 @@
     static final Function<Integer, Stream<Integer>> integerRangeMapper
             = e -> IntStream.range(0, e).boxed();
 
+    @Test
     public void testFlatMap() {
         String[] stringsArray = {"hello", "there", "", "yada"};
         Stream<String> strings = Arrays.asList(stringsArray).stream();
@@ -149,11 +151,24 @@
         exerciseOps(data, s -> s.flatMap((Integer e) -> IntStream.range(0, e).boxed().limit(10)));
     }
 
+    @Test
+    public void testOpsShortCircuit() {
+        AtomicInteger count = new AtomicInteger();
+        Stream.of(0).flatMap(i -> IntStream.range(0, 100).boxed()).
+                peek(i -> count.incrementAndGet()).
+                limit(10).toArray();
+        assertEquals(count.get(), 10);
+    }
+
     //
 
     @Test(dataProvider = "IntStreamTestData", dataProviderClass = IntStreamTestDataProvider.class)
     public void testIntOps(String name, TestData.OfInt data) {
-        Collection<Integer> result = exerciseOps(data, s -> s.flatMap(i -> Collections.singleton(i).stream().mapToInt(j -> j)));
+        Collection<Integer> result = exerciseOps(data, s -> s.flatMap(IntStream::of));
+        assertEquals(data.size(), result.size());
+        assertContents(data, result);
+
+        result = exerciseOps(data, s -> s.boxed().flatMapToInt(IntStream::of));
         assertEquals(data.size(), result.size());
         assertContents(data, result);
 
@@ -165,13 +180,35 @@
     public void testIntOpsX(String name, TestData.OfInt data) {
         exerciseOps(data, s -> s.flatMap(e -> IntStream.range(0, e)));
         exerciseOps(data, s -> s.flatMap(e -> IntStream.range(0, e).limit(10)));
+
+        exerciseOps(data, s -> s.boxed().flatMapToInt(e -> IntStream.range(0, e)));
+        exerciseOps(data, s -> s.boxed().flatMapToInt(e -> IntStream.range(0, e).limit(10)));
+    }
+
+    @Test
+    public void testIntOpsShortCircuit() {
+        AtomicInteger count = new AtomicInteger();
+        IntStream.of(0).flatMap(i -> IntStream.range(0, 100)).
+                peek(i -> count.incrementAndGet()).
+                limit(10).toArray();
+        assertEquals(count.get(), 10);
+
+        count.set(0);
+        Stream.of(0).flatMapToInt(i -> IntStream.range(0, 100)).
+                peek(i -> count.incrementAndGet()).
+                limit(10).toArray();
+        assertEquals(count.get(), 10);
     }
 
     //
 
     @Test(dataProvider = "LongStreamTestData", dataProviderClass = LongStreamTestDataProvider.class)
     public void testLongOps(String name, TestData.OfLong data) {
-        Collection<Long> result = exerciseOps(data, s -> s.flatMap(i -> Collections.singleton(i).stream().mapToLong(j -> j)));
+        Collection<Long> result = exerciseOps(data, s -> s.flatMap(LongStream::of));
+        assertEquals(data.size(), result.size());
+        assertContents(data, result);
+
+        result = exerciseOps(data, s -> s.boxed().flatMapToLong(LongStream::of));
         assertEquals(data.size(), result.size());
         assertContents(data, result);
 
@@ -185,11 +222,30 @@
         exerciseOps(data, s -> s.flatMap(e -> LongStream.range(0, e).limit(10)));
     }
 
+    @Test
+    public void testLongOpsShortCircuit() {
+        AtomicInteger count = new AtomicInteger();
+        LongStream.of(0).flatMap(i -> LongStream.range(0, 100)).
+                peek(i -> count.incrementAndGet()).
+                limit(10).toArray();
+        assertEquals(count.get(), 10);
+
+        count.set(0);
+        Stream.of(0).flatMapToLong(i -> LongStream.range(0, 100)).
+                peek(i -> count.incrementAndGet()).
+                limit(10).toArray();
+        assertEquals(count.get(), 10);
+    }
+
     //
 
     @Test(dataProvider = "DoubleStreamTestData", dataProviderClass = DoubleStreamTestDataProvider.class)
     public void testDoubleOps(String name, TestData.OfDouble data) {
-        Collection<Double> result = exerciseOps(data, s -> s.flatMap(i -> Collections.singleton(i).stream().mapToDouble(j -> j)));
+        Collection<Double> result = exerciseOps(data, s -> s.flatMap(DoubleStream::of));
+        assertEquals(data.size(), result.size());
+        assertContents(data, result);
+
+        result = exerciseOps(data, s -> s.boxed().flatMapToDouble(DoubleStream::of));
         assertEquals(data.size(), result.size());
         assertContents(data, result);
 
@@ -202,4 +258,19 @@
         exerciseOps(data, s -> s.flatMap(e -> IntStream.range(0, (int) e).asDoubleStream()));
         exerciseOps(data, s -> s.flatMap(e -> IntStream.range(0, (int) e).limit(10).asDoubleStream()));
     }
+
+    @Test
+    public void testDoubleOpsShortCircuit() {
+        AtomicInteger count = new AtomicInteger();
+        DoubleStream.of(0).flatMap(i -> IntStream.range(0, 100).asDoubleStream()).
+                peek(i -> count.incrementAndGet()).
+                limit(10).toArray();
+        assertEquals(count.get(), 10);
+
+        count.set(0);
+        Stream.of(0).flatMapToDouble(i -> IntStream.range(0, 100).asDoubleStream()).
+                peek(i -> count.incrementAndGet()).
+                limit(10).toArray();
+        assertEquals(count.get(), 10);
+    }
 }
--- a/test/jdk/javax/imageio/spi/AppletContextTest/BadPluginConfigurationTest.sh	Thu Jan 18 11:22:28 2018 +0530
+++ b/test/jdk/javax/imageio/spi/AppletContextTest/BadPluginConfigurationTest.sh	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 #!/bin/ksh -p
-# Copyright (c) 2005, 2017, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2005, 2018, 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
@@ -86,8 +86,24 @@
 
 # Checking for proper OS
 OS=`uname -s`
+MKTEMP="mktemp"
 case "$OS" in
-   SunOS | Linux | Darwin )
+   AIX )
+      FILESEP="/"
+      PATHSEP=":"
+      TMP=`cd /tmp; pwd -P`
+
+      type ${MKTEMP} > /dev/null 2>&1
+
+      if ! [ $? -ne 0 ] ; then 
+        MKTEMP="/opt/freeware/bin/mktemp"
+      fi
+      if ! [ -e ${MKTEMP} ] ; then 
+        pass "Test skipped because no mktemp found on this machine"
+      fi
+      ;;
+
+   Darwin | Linux | SunOS )
       FILESEP="/"
       PATHSEP=":"
       TMP=`cd /tmp; pwd -P`
@@ -180,7 +196,7 @@
 # app have file read permission for all subdirs of the
 # scratch dir
 
-PLUGINDST_DIR=$(mktemp -d ${TMP}/iio_test.XXXXXXXX)
+PLUGINDST_DIR=$(${MKTEMP} -d ${TMP}/iio_test.XXXXXXXX)
 echo "Created PLUGINDST_DIR as ${PLUGINDST_DIR}"
 
 TEST_PLUGIN=dummy.jar
--- a/test/jdk/javax/management/remote/nonLocalAccess/NonLocalJMXRemoteTest.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/test/jdk/javax/management/remote/nonLocalAccess/NonLocalJMXRemoteTest.java	Fri Jan 19 09:32:10 2018 -0800
@@ -43,14 +43,37 @@
  * This tests the SingleEntryRegistry implemented by JMX.
  * This test is a manual test and uses JMX running on a *different* host.
  * JMX can be enabled in any Java runtime; for example:
- * login or ssh to the different host and invoke rmiregistry with arguments below.
+ *
+ * Note: Use remote host with latest JDK update release for invoking rmiregistry.
+ *
+ * Note: Test should be ran twice once using arg1 and once using arg2.
+ *
+ * login or ssh to the remote host and invoke rmiregistry with arg1.
  * It will not show any output.
- * {@code $JDK_HOME/bin/rmiregistry \
+ * Execute the test, after test completes execution, stop the server.
+ *
+ * repeat above step using arg2 and execute the test.
+ *
+ *
+ * arg1: {@code $JDK_HOME/bin/rmiregistry \
  *         -J-Dcom.sun.management.jmxremote.port=8888 \
  *         -J-Dcom.sun.management.jmxremote.local.only=false \
  *         -J-Dcom.sun.management.jmxremote.ssl=false \
  *         -J-Dcom.sun.management.jmxremote.authenticate=false
  * }
+ *
+ *
+ * replace "jmx-registry-host" with the hostname or IP address of the remote host
+ * for property "-J-Dcom.sun.management.jmxremote.host" below.
+ *
+ * arg2: {@code $JDK_HOME/bin/rmiregistry \
+ *         -J-Dcom.sun.management.jmxremote.port=8888 \
+ *         -J-Dcom.sun.management.jmxremote.local.only=false \
+ *         -J-Dcom.sun.management.jmxremote.ssl=false \
+ *         -J-Dcom.sun.management.jmxremote.authenticate=false \
+ *         -J-Dcom.sun.management.jmxremote.host="jmx-registry-host"
+ * }
+ *
  * On the first host modify the @run command above to replace "jmx-registry-host"
  * with the hostname or IP address of the different host and run the test with jtreg.
  */
@@ -123,6 +146,7 @@
             if (asIndex < 0 ||
                     disallowIndex < 0 ||
                     nonLocalHostIndex < 0 ) {
+                System.out.println("Exception message is " + msg);
                 throw new RuntimeException("exception message is malformed", t);
             }
             System.out.printf("Found expected AccessException: %s%n%n", t);
--- a/test/jdk/sun/security/mscapi/ShortRSAKey1024.sh	Thu Jan 18 11:22:28 2018 +0530
+++ b/test/jdk/sun/security/mscapi/ShortRSAKey1024.sh	Fri Jan 19 09:32:10 2018 -0800
@@ -1,7 +1,7 @@
 #!/bin/sh
 
 #
-# Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2012, 2018, 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
@@ -50,7 +50,7 @@
 
 OS=`uname -s`
 case "$OS" in
-  SunOS | Linux | Darwin | CYGWIN* )
+  AIX | CYGWIN* | Darwin | Linux | SunOS )
     FS="/"
     ;;
   Windows_* )
--- a/test/jdk/sun/security/pkcs11/KeyAgreement/TestDH.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/test/jdk/sun/security/pkcs11/KeyAgreement/TestDH.java	Fri Jan 19 09:32:10 2018 -0800
@@ -28,8 +28,8 @@
  * @author Andreas Sterbenz
  * @library ..
  * @modules jdk.crypto.cryptoki
- * @run main/othervm TestDH
- * @run main/othervm TestDH sm
+ * @run main/othervm -Djdk.crypto.KeyAgreement.legacyKDF=true TestDH
+ * @run main/othervm -Djdk.crypto.KeyAgreement.legacyKDF=true TestDH sm
  */
 
 import java.security.KeyPair;
--- a/test/jdk/sun/security/pkcs11/PKCS11Test.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/test/jdk/sun/security/pkcs11/PKCS11Test.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2018, 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
@@ -443,7 +443,17 @@
 
         // the index after whitespace after nssHeader
         int afterheader = s.indexOf("NSS", i) + 4;
-        String version = s.substring(afterheader, s.indexOf(' ', afterheader));
+        int nextSpaceIndex = s.indexOf(' ', afterheader);
+
+        // If the next space is not found,
+        // it has to print the content for further investigation.
+        if (nextSpaceIndex == -1) {
+            System.out.println("===== Content start =====");
+            System.out.println(s);
+            System.out.println("===== Content end =====");
+        }
+
+        String version = s.substring(afterheader, nextSpaceIndex);
 
         // If a "dot dot" release, strip the extra dots for double parsing
         String[] dot = version.split("\\.");
@@ -624,6 +634,7 @@
             "/usr/lib64/"});
         osMap.put("Linux-ppc64-64", new String[]{"/usr/lib64/"});
         osMap.put("Linux-ppc64le-64", new String[]{"/usr/lib64/"});
+        osMap.put("Linux-s390x-64", new String[]{"/usr/lib64/"});
         osMap.put("Windows-x86-32", new String[]{
             PKCS11_BASE + "/nss/lib/windows-i586/".replace('/', SEP)});
         osMap.put("Windows-amd64-64", new String[]{
--- a/test/jdk/sun/security/ssl/ClientHandshaker/RSAExport.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/test/jdk/sun/security/ssl/ClientHandshaker/RSAExport.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2008, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 2017, 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
@@ -419,6 +419,7 @@
         // reset the security property to make sure that the algorithms
         // and keys used in this test are not disabled.
         Security.setProperty("jdk.certpath.disabledAlgorithms", "MD2");
+        Security.setProperty("jdk.tls.disabledAlgorithms", "MD2");
 
         if (debug)
             System.setProperty("javax.net.debug", "all");
--- a/test/jdk/sun/security/tools/keytool/i18n.sh	Thu Jan 18 11:22:28 2018 +0530
+++ b/test/jdk/sun/security/tools/keytool/i18n.sh	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -44,7 +44,7 @@
 # set platform-dependent variables
 OS=`uname -s`
 case "$OS" in
-  SunOS | Linux | Darwin )
+  AIX | Darwin | Linux | SunOS )
     NULL=/dev/null
     PS=":"
     FS="/"
--- a/test/jdk/sun/text/resources/LocaleData	Thu Jan 18 11:22:28 2018 +0530
+++ b/test/jdk/sun/text/resources/LocaleData	Fri Jan 19 09:32:10 2018 -0800
@@ -6396,7 +6396,6 @@
 CurrencyNames//ang=Netherlands Antillean Guilder
 CurrencyNames//awg=Aruban Florin
 CurrencyNames//azm=Azerbaijani Manat (1993-2006)
-CurrencyNames//azn=Azerbaijani Manat
 CurrencyNames//bbd=Barbadian Dollar
 CurrencyNames//bdt=Bangladeshi Taka
 CurrencyNames//bgn=Bulgarian Lev
--- a/test/jdk/sun/text/resources/LocaleDataTest.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/test/jdk/sun/text/resources/LocaleDataTest.java	Fri Jan 19 09:32:10 2018 -0800
@@ -38,7 +38,7 @@
  *      7114053 7074882 7040556 8008577 8013836 8021121 6192407 6931564 8027695
  *      8017142 8037343 8055222 8042126 8074791 8075173 8080774 8129361 8134916
  *      8145136 8145952 8164784 8037111 8081643 7037368 8178872 8185841 8190918
- *      8187946
+ *      8187946 8195478
  * @summary Verify locale data
  * @modules java.base/sun.util.resources
  * @modules jdk.localedata
--- a/test/langtools/jdk/javadoc/doclet/testCopyFiles/TestCopyFiles.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/test/langtools/jdk/javadoc/doclet/testCopyFiles/TestCopyFiles.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -23,7 +23,7 @@
 
 /*
  * @test
- * @bug  8157349 8185985
+ * @bug  8157349 8185985 8194953
  * @summary  test copy of doc-files, and its contents for HTML meta content.
  * @library  ../lib
  * @modules jdk.javadoc/jdk.javadoc.internal.tool
@@ -258,4 +258,16 @@
                 "A named package in an unnamed module"
         );
     }
+
+    @Test
+    void testCopyThrough() {
+        javadoc("-d", "copy",
+                "-sourcepath", testSrc("packages"),
+                "p2");
+        checkExit(Exit.OK);
+        checkOutput("p2/doc-files/case1.html", true, "<!-- Generated by javadoc");
+        checkOutput("p2/doc-files/case2.html", false, "<!-- Generated by javadoc");
+        checkOutput("p2/doc-files/case3.html", false, "<!-- Generated by javadoc");
+        checkOutput("p2/doc-files/case4.html", false, "<!-- Generated by javadoc");
+    }
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/langtools/jdk/javadoc/doclet/testCopyFiles/packages/p2/Foo.java	Fri Jan 19 09:32:10 2018 -0800
@@ -0,0 +1,34 @@
+/*
+ * Copyright (c) 2018, 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.
+ */
+
+ /**
+  * A test class.
+  */
+package p2;
+
+/**
+ * A test class.
+ */
+public class Foo {}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/langtools/jdk/javadoc/doclet/testCopyFiles/packages/p2/doc-files/case1.html	Fri Jan 19 09:32:10 2018 -0800
@@ -0,0 +1,39 @@
+<!doctype html>
+
+<!--
+/*
+ * Copyright (c) 2018, 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.
+ */
+-->
+
+<html lang="en">
+  <head>
+    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
+    <title>Case 1</title>
+  </head>
+  <body>
+     This should be translated with a navbar, and should have
+     the "Generated by javadoc blah" signature.
+  </body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/langtools/jdk/javadoc/doclet/testCopyFiles/packages/p2/doc-files/case2.html	Fri Jan 19 09:32:10 2018 -0800
@@ -0,0 +1,44 @@
+<!doctype html>
+
+<!--
+/*
+ * Copyright (c) 2018, 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.
+ */
+-->
+
+<html lang="en">
+  <head>
+    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
+    <title>Case 2</title>
+    <style type="text/css">
+      body {
+        font-family: Helvetica, Arial, sans-serif;
+        font-size: 14px;
+      }
+    </style>
+  </head>
+  <body>
+  This should be copied directly, with no modifications.
+  </body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/langtools/jdk/javadoc/doclet/testCopyFiles/packages/p2/doc-files/case3.html	Fri Jan 19 09:32:10 2018 -0800
@@ -0,0 +1,42 @@
+<!doctype html>
+
+<!--
+/*
+ * Copyright (c) 2018, 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.
+ */
+-->
+
+<html lang="en">
+  <head>
+    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
+    <title>Case 3</title>
+      <style>
+        h1 {color:red;}
+        p {color:blue;}
+      </style>
+  </head>
+  <body>
+  This should be copied directly, with no modifications.
+  </body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/langtools/jdk/javadoc/doclet/testCopyFiles/packages/p2/doc-files/case4.html	Fri Jan 19 09:32:10 2018 -0800
@@ -0,0 +1,39 @@
+<!doctype html>
+
+<!--
+/*
+ * Copyright (c) 2018, 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.
+ */
+-->
+
+<html lang="en">
+  <head>
+    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
+    <title>Case 3</title>
+    <link rel="stylesheet" type="text/css" href="theme.css"> 
+  </head>
+  <body>
+  This should be copied directly, with no modifications.
+  </body>
+</html>
--- a/test/langtools/jdk/jshell/InaccessibleExpressionTest.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/test/langtools/jdk/jshell/InaccessibleExpressionTest.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2017, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -22,7 +22,7 @@
  */
 
 /*
- * @test 8190939
+ * @test 8190939 8191842
  * @summary test expressions whose type is inaccessible
  * @modules jdk.compiler/com.sun.tools.javac.api
  *          jdk.compiler/com.sun.tools.javac.main
@@ -86,6 +86,8 @@
         assertEval(list.name() + ".size()", "0");
         VarSnippet one = varKey(assertEval("priv()", "One"));
         assertEquals(one.typeName(), "priv.GetPriv.Count");
+        assertEval("var v = down();", "Packp");
+        assertDeclareFail("v.toString()", "compiler.err.not.def.access.class.intf.cant.access");
     }
 
     public void testInternal() {
--- a/test/langtools/jdk/jshell/ToolSimpleTest.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/test/langtools/jdk/jshell/ToolSimpleTest.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -23,7 +23,7 @@
 
 /*
  * @test
- * @bug 8153716 8143955 8151754 8150382 8153920 8156910 8131024 8160089 8153897 8167128 8154513 8170015 8170368 8172102 8172103  8165405 8173073 8173848 8174041 8173916 8174028 8174262 8174797 8177079 8180508 8177466 8172154 8192979
+ * @bug 8153716 8143955 8151754 8150382 8153920 8156910 8131024 8160089 8153897 8167128 8154513 8170015 8170368 8172102 8172103  8165405 8173073 8173848 8174041 8173916 8174028 8174262 8174797 8177079 8180508 8177466 8172154 8192979 8191842
  * @summary Simple jshell tool tests
  * @modules jdk.compiler/com.sun.tools.javac.api
  *          jdk.compiler/com.sun.tools.javac.main
@@ -786,7 +786,11 @@
                 (a) -> assertCommandOutputContains(a, "var r1 = new Object() {}", "r1"),
                 (a) -> assertCommandOutputContains(a, "/vars r1", "|    <anonymous class extending Object> r1 = "),
                 (a) -> assertCommandOutputContains(a, "var r2 = new Runnable() { public void run() { } }", "r2"),
-                (a) -> assertCommandOutputContains(a, "/vars r2", "|    <anonymous class implementing Runnable> r2 = ")
+                (a) -> assertCommandOutputContains(a, "/vars r2", "|    <anonymous class implementing Runnable> r2 = "),
+                (a) -> assertCommandOutputContains(a, "import java.util.stream.*;", ""),
+                (a) -> assertCommandOutputContains(a, "var list = Stream.of(1, 2, 3).map(j -> new Object() { int i = j; }).collect(Collectors.toList());",
+                                                      "list"),
+                (a) -> assertCommandOutputContains(a, "/vars list", "|    List<<anonymous class extending Object>> list = ")
         );
     }
 }
--- a/test/langtools/jdk/jshell/TypeNameTest.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/test/langtools/jdk/jshell/TypeNameTest.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -23,7 +23,7 @@
 
 /*
  * @test
- * @bug 8144903 8171981 8191802
+ * @bug 8144903 8171981 8191802 8191842
  * @summary Tests for determining the type from the expression
  * @build KullaTesting TestingInputStream
  * @run testng TypeNameTest
@@ -38,8 +38,12 @@
 
 
     private void assertType(String expr, String type) {
+        assertType(expr, type, type);
+    }
+
+    private void assertType(String expr, String type, String inferType) {
         assertEquals(varKey(assertEval(expr)).typeName(), type);
-        assertInferredType(expr, type);
+        assertInferredType(expr, inferType);
     }
 
     public void testTypeInference() {
@@ -58,7 +62,7 @@
         assertType("d.getS()", "D<?>");
         assertType("null", "Object");
         assertType("Class.forName( \"java.util.ArrayList\" )", "Class<?>");
-        assertType("new ArrayList<Boolean>() {}", "ArrayList<Boolean>");
+        assertType("new ArrayList<Boolean>() {}", "<anonymous class extending ArrayList<Boolean>>", "ArrayList<Boolean>");
         assertType("new ArrayList<String>().stream()", "java.util.stream.Stream<String>");
         assertType("Arrays.asList( 1, 2, 3)", "List<Integer>");
         assertType("new ArrayList().getClass().getClass()", "Class<? extends Class>");
@@ -188,7 +192,7 @@
         assertType("arrayOf(99)[0]", "Integer");
 
         assertEval("<Z> Z choose(Z z1, Z z2) { return z1; }");
-        assertType("choose(1, 1L);", "Object");
+        assertType("choose(1, 1L);", "Number&Comparable<? extends Number&Comparable<?>>", "Object");
     }
 
     public void testVariableTypeName() {
@@ -215,7 +219,7 @@
     public void testAnonymousClassName() {
         assertEval("class C {}");
         assertType("new C();", "C");
-        assertType("new C() { int x; };", "C");
+        assertType("new C() { int x; };", "<anonymous class extending C>", "C");
     }
 
     public void testCapturedTypeName() {
@@ -243,7 +247,7 @@
         assertType("test1.get()", "CharSequence");
         assertEval("class Test2<X extends Number & CharSequence> { public X get() { return null; } }");
         assertEval("Test2<?> test2 = new Test2<>();");
-        assertType("test2.get()", "Object");
+        assertType("test2.get()", "Number&CharSequence", "Object");
         assertEval("class Test3<T> { T[][] get() { return null; } }");
         assertEval("Test3<? extends String> test3 = new Test3<>();");
         assertType("test3.get()", "String[][]");
--- a/test/langtools/jdk/jshell/VariablesTest.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/test/langtools/jdk/jshell/VariablesTest.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -23,12 +23,15 @@
 
 /*
  * @test
- * @bug 8144903 8177466
+ * @bug 8144903 8177466 8191842
  * @summary Tests for EvaluationState.variables
- * @build KullaTesting TestingInputStream ExpectedDiagnostic
+ * @library /tools/lib
+ * @build Compiler KullaTesting TestingInputStream ExpectedDiagnostic
  * @run testng VariablesTest
  */
 
+import java.nio.file.Path;
+import java.nio.file.Paths;
 import java.util.List;
 import javax.tools.Diagnostic;
 
@@ -37,6 +40,7 @@
 import jdk.jshell.VarSnippet;
 import jdk.jshell.Snippet.SubKind;
 import jdk.jshell.SnippetEvent;
+import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
 
 import static java.util.stream.Collectors.toList;
@@ -362,5 +366,157 @@
         assertEval("class O2 { public class Inner { public Inner(int i) { } public String test() { return \"good\"; } } }");
         assertEval("var r5 = new O2().new Inner(1) { public String get() { return \"good\"; } };");
         assertEval("r5.get()", "\"good\"");
+        assertEval("<Z> Z identity(Z z) { return z; }");
+        assertEval("var r6 = identity(new Object() { String s = \"good\"; });");
+        assertEval("r6.s", "\"good\"");
+        assertEval("interface I<B, C> { C get(B b); }");
+        assertEval("<A, B, C> C cascade(A a, I<A, B> c1, I<B, C> c2) { return c2.get(c1.get(a)); }");
+        assertEval("var r7 = cascade(\"good\", a -> new Object() { String s = a; }, b -> new java.util.ArrayList<String>(5) { String s = b.s; });");
+        assertEval("r7.s", "\"good\"");
+        assertEval("var r8 = cascade(\"good\", a -> new Object() { String s = a; public String getS() { return s; } }, b -> new java.util.ArrayList<String>(5) { String s = b.getS(); public String getS() { return s; } });");
+        assertEval("r8.getS()", "\"good\"");
+        assertEval("var r9 = new Object() { class T { class Inner { public String g() { return outer(); } } public String outer() { return \"good\"; } public String test() { return new Inner() {}.g(); } } public String test() { return new T().test(); } };");
+        assertEval("r9.test()", "\"good\"");
+        assertEval("var nested1 = new Object() { class N { public String get() { return \"good\"; } } };");
+        assertEval("nested1.new N().get()", "\"good\"");
+        assertEval("var nested2 = cascade(\"good\", a -> new Object() { abstract class G { abstract String g(); } G g = new G() { String g() { return a; } }; }, b -> new java.util.ArrayList<String>(5) { String s = b.g.g(); });");
+        assertEval("nested2.s", "\"good\"");
+        assertEval("<A, B> B convert(A a, I<A, B> c) { return c.get(a); }");
+        assertEval("var r10 = convert(\"good\", a -> new api.C(12) { public String val = \"\" + i + s + l + a; } );");
+        assertEval("r10.val", "\"12empty[empty]good\"");
+        assertEval("var r11 = convert(\"good\", a -> new api.C(\"a\") { public String val = \"\" + i + s + l + a; } );");
+        assertEval("r11.val", "\"3a[empty]good\"");
+        assertEval("import api.C;");
+        assertEval("var r12 = convert(\"good\", a -> new C(java.util.List.of(\"a\")) { public String val = \"\" + i + s + l + a; } );");
+        assertEval("r12.val", "\"4empty[a]good\"");
+        assertEval("var r13 = convert(\"good\", a -> new api.G<String>(java.util.List.of(\"b\")) { public String val = \"\" + l + a; } );");
+        assertEval("r13.val", "\"[b]good\"");
+        assertEval("var r14 = convert(\"good\", a -> new api.J<String>() { public java.util.List<String> get() { return java.util.List.of(a, \"c\"); } } );");
+        assertEval("r14.get()", "[good, c]");
+        assertEval("var r15a = new java.util.ArrayList<String>();");
+        assertEval("r15a.add(\"a\");");
+        assertEval("var r15b = r15a.get(0);");
+        assertEval("r15b", "\"a\"");
+    }
+
+    public void test8191842() {
+        assertEval("import java.util.stream.*;");
+        assertEval("var list = Stream.of(1, 2, 3).map(j -> new Object() { int i = j; }).collect(Collectors.toList());");
+        assertEval("list.stream().map(a -> String.valueOf(a.i)).collect(Collectors.joining(\", \"));", "\"1, 2, 3\"");
+    }
+
+    public void lvtiRecompileDependentsWithIntersectionTypes() {
+        assertEval("<Z extends Runnable & CharSequence> Z get1() { return null; }", added(VALID));
+        VarSnippet var = varKey(assertEval("var i1 = get1();", added(VALID)));
+        assertEval("import java.util.stream.*;", added(VALID),
+                                                 ste(var, VALID, VALID, true, MAIN_SNIPPET));
+        assertEval("void t1() { i1.run(); i1.length(); }", added(VALID));
+    }
+
+    public void arrayInit() {
+        assertEval("int[] d = {1, 2, 3};");
+    }
+
+    public void testAnonymousVar() {
+        assertEval("new Object() { public String get() { return \"a\"; } }");
+        assertEval("$1.get()", "\"a\"");
+    }
+
+    public void testIntersectionVar() {
+        assertEval("<Z extends Runnable & CharSequence> Z get() { return null; }", added(VALID));
+        assertEval("get();", added(VALID));
+        assertEval("void t1() { $1.run(); $1.length(); }", added(VALID));
+    }
+
+    public void multipleCaptures() {
+        assertEval("class D { D(int foo, String bar) { this.foo = foo; this.bar = bar; } int foo; String bar; } ");
+        assertEval("var d = new D(34, \"hi\") { String z = foo + bar; };");
+        assertEval("d.z", "\"34hi\"");
+    }
+
+    public void multipleAnonymous() {
+        VarSnippet v1 = varKey(assertEval("new Object() { public int i = 42; public int i1 = i; public int m1() { return i1; } };"));
+        VarSnippet v2 = varKey(assertEval("new Object() { public int i = 42; public int i2 = i; public int m2() { return i2; } };"));
+        assertEval(v1.name() + ".i", "42");
+        assertEval(v1.name() + ".i1", "42");
+        assertEval(v1.name() + ".m1()", "42");
+        assertDeclareFail(v1.name() + ".i2",
+                          new ExpectedDiagnostic("compiler.err.cant.resolve.location", 0, 5, 2,
+                                                 -1, -1, Diagnostic.Kind.ERROR));
+        assertEval(v2.name() + ".i", "42");
+        assertEval(v2.name() + ".i2", "42");
+        assertEval(v2.name() + ".m2()", "42");
+        assertDeclareFail(v2.name() + ".i1",
+                          new ExpectedDiagnostic("compiler.err.cant.resolve.location", 0, 5, 2,
+                                                 -1, -1, Diagnostic.Kind.ERROR));
+    }
+
+    public void displayName() {
+        assertVarDisplayName("var v1 = 234;", "int");
+        assertVarDisplayName("var v2 = new int[] {234};", "int[]");
+        assertEval("<Z extends Runnable & CharSequence> Z get() { return null; }", added(VALID));
+        assertVarDisplayName("var v3 = get();", "CharSequence&Runnable");
+        assertVarDisplayName("var v4a = new java.util.ArrayList<String>();", "java.util.ArrayList<String>");
+        assertEval("v4a.add(\"a\");");
+        assertVarDisplayName("var v4b = v4a.get(0);", "String");
+        assertVarDisplayName("var v5 = new Object() { };", "<anonymous class extending Object>");
+        assertVarDisplayName("var v6 = new Runnable() { public void run() { } };", "<anonymous class implementing Runnable>");
+    }
+
+    private void assertVarDisplayName(String var, String typeName) {
+        assertEquals(varKey(assertEval(var)).typeName(), typeName);
+    }
+
+    @BeforeMethod
+    @Override
+    public void setUp() {
+        Path path = Paths.get("cp");
+        Compiler compiler = new Compiler();
+        compiler.compile(path,
+                "package api;\n" +
+                "\n" +
+                "import java.util.List;\n" +
+                "\n" +
+                "public class C {\n" +
+                "   public int i;\n" +
+                "   public String s;\n" +
+                "   public List<String> l;\n" +
+                "   public C(int i) {\n" +
+                "       this.i = i;\n" +
+                "       this.s = \"empty\";\n" +
+                "       this.l = List.of(\"empty\");\n" +
+                "   }\n" +
+                "   public C(String s) {\n" +
+                "       this.i = 3;\n" +
+                "       this.s = s;\n" +
+                "       this.l = List.of(\"empty\");\n" +
+                "   }\n" +
+                "   public C(List<String> l) {\n" +
+                "       this.i = 4;\n" +
+                "       this.s = \"empty\";\n" +
+                "       this.l = l;\n" +
+                "   }\n" +
+                "}\n",
+                "package api;\n" +
+                "\n" +
+                "import java.util.List;\n" +
+                "\n" +
+                "public class G<T> {\n" +
+                "   public List<T> l;\n" +
+                "   public G(List<T> l) {\n" +
+                "       this.l = l;\n" +
+                "   }\n" +
+                "}\n",
+                "package api;\n" +
+                "\n" +
+                "import java.util.List;\n" +
+                "\n" +
+                "public interface J<T> {\n" +
+                "   public List<T> get();\n" +
+                "}\n");
+        String tpath = compiler.getPath(path).toString();
+        setUp(b -> b
+                .remoteVMOptions("--class-path", tpath)
+                .compilerOptions("--class-path", tpath));
     }
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/langtools/tools/javac/diags/examples/FutureVarNotAllowed.java	Fri Jan 19 09:32:10 2018 -0800
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) 2016, 2018, 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.
+ */
+
+// key: compiler.warn.var.not.allowed
+// options: --release 9
+
+class var { }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/langtools/tools/javac/lambda/T8195598.java	Fri Jan 19 09:32:10 2018 -0800
@@ -0,0 +1,49 @@
+/*
+ * Copyright (c) 2018, 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.
+ */
+
+/*
+ * @test
+ * @bug 8195598
+ * @summary Reference to overloaded method is ambiguous with 3 methods but works with 2
+ * @compile T8195598.java
+ */
+
+import java.util.concurrent.*;
+import java.util.function.*;
+
+class T8195598 {
+    public CompletableFuture<?> test() {
+        return ok(() -> System.out.append("aaa"));
+    }
+    public <T> CompletableFuture<T> ok(Supplier<T> action) {
+        return CompletableFuture.supplyAsync(action);
+    }
+    public <T> CompletableFuture<T> ok(T body) {
+        return CompletableFuture.completedFuture(body);
+    }
+    public CompletableFuture<Void> ok(Runnable action) {
+        return CompletableFuture.runAsync(action);
+    }
+}
--- a/test/langtools/tools/javac/lvti/ParserTest.java	Thu Jan 18 11:22:28 2018 +0530
+++ b/test/langtools/tools/javac/lvti/ParserTest.java	Fri Jan 19 09:32:10 2018 -0800
@@ -1,8 +1,8 @@
 /*
  * @test /nodynamiccopyright/
- * @bug 8177466
+ * @bug 8177466 8189146
+ * @compile/ref=ParserTest9.out -XDrawDiagnostics --release 9 ParserTest.java
  * @summary Add compiler support for local variable type-inference
- * @compile -source 9 ParserTest.java
  * @compile/fail/ref=ParserTest.out -XDrawDiagnostics ParserTest.java
  */
 
@@ -11,7 +11,7 @@
 import java.util.function.Function;
 import java.util.List;
 
-class ParserTest<var> {
+class ParserTest<var extends AutoCloseable> {
     static class TestClass {
         static class var { } //illegal
     }
@@ -33,7 +33,7 @@
 
     @interface DA { }
 
-    static class var extends RuntimeException { } //illegal
+    static abstract class var extends RuntimeException implements AutoCloseable { } //illegal
 
     var x = null; //illegal
 
@@ -68,4 +68,10 @@
         boolean b1 = o instanceof var; //error
         Object o2 = (var)o; //error
     }
+
+    void test4() throws Exception {
+        try (final var resource1 = null; // ok
+             var resource2 = null) {     // ok
+        }
+    }
 }
--- a/test/langtools/tools/javac/lvti/ParserTest.out	Thu Jan 18 11:22:28 2018 +0530
+++ b/test/langtools/tools/javac/lvti/ParserTest.out	Fri Jan 19 09:32:10 2018 -0800
@@ -3,7 +3,7 @@
 ParserTest.java:20:19: compiler.err.var.not.allowed: var
 ParserTest.java:24:14: compiler.err.var.not.allowed: var
 ParserTest.java:28:20: compiler.err.var.not.allowed: var
-ParserTest.java:36:18: compiler.err.var.not.allowed: var
+ParserTest.java:36:27: compiler.err.var.not.allowed: var
 ParserTest.java:38:5: compiler.err.var.not.allowed.here
 ParserTest.java:41:15: compiler.err.var.not.allowed.array
 ParserTest.java:42:13: compiler.err.var.not.allowed.array
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/langtools/tools/javac/lvti/ParserTest9.out	Fri Jan 19 09:32:10 2018 -0800
@@ -0,0 +1,7 @@
+ParserTest.java:14:18: compiler.warn.var.not.allowed
+ParserTest.java:16:22: compiler.warn.var.not.allowed
+ParserTest.java:20:19: compiler.warn.var.not.allowed
+ParserTest.java:24:14: compiler.warn.var.not.allowed
+ParserTest.java:28:20: compiler.warn.var.not.allowed
+ParserTest.java:36:27: compiler.warn.var.not.allowed
+6 warnings