changeset 51964:d034d46065fb

Merge
author aph
date Mon, 01 Oct 2018 09:56:45 +0100
parents 8f0f7f2ae20b 628909466216
children 358a3b99198a
files src/java.desktop/share/classes/com/sun/awt/SecurityWarning.java src/java.desktop/share/classes/sun/applet/AppletClassLoader.java src/java.desktop/share/classes/sun/applet/AppletSecurity.java src/java.desktop/share/classes/sun/applet/AppletThreadGroup.java src/java.desktop/share/classes/sun/awt/HToolkit.java src/java.desktop/unix/native/libawt_xawt/awt/HPkeysym.h test/jdk/com/sun/awt/SecurityWarning/CustomSecurityManager.java test/jdk/com/sun/awt/SecurityWarning/GetSizeShouldNotReturnZero.java test/jdk/com/sun/awt/TEST.properties test/jdk/java/awt/dnd/BadSerializaionTest/BadSerializationTest.java test/jdk/java/awt/dnd/BadSerializaionTest/badAction test/jdk/java/awt/dnd/BadSerializaionTest/good test/jdk/java/awt/dnd/BadSerializaionTest/noEvents test/jdk/java/awt/dnd/BadSerializaionTest/nullComponent test/jdk/java/awt/dnd/BadSerializaionTest/nullDragSource test/jdk/java/awt/dnd/BadSerializaionTest/nullOrigin test/jdk/sun/security/tools/keytool/autotest.sh test/jdk/sun/security/tools/keytool/standard.sh test/langtools/tools/javadoc/api/basic/IsSupportedOptionTest.java
diffstat 269 files changed, 6410 insertions(+), 4846 deletions(-) [+]
line wrap: on
line diff
--- a/.hgtags	Wed Sep 26 18:11:00 2018 +0100
+++ b/.hgtags	Mon Oct 01 09:56:45 2018 +0100
@@ -513,3 +513,4 @@
 8f594f75e0547d4ca16649cb3501659e3155e81b jdk-12+10
 f0f5d23449d31f1b3580c8a73313918cafeaefd7 jdk-12+11
 15094d12a632f452a2064318a4e416d0c7a9ce0c jdk-12+12
+511a9946f83e3e3c7b9dbe1840367063fb39b4e1 jdk-12+13
--- a/make/autoconf/hotspot.m4	Wed Sep 26 18:11:00 2018 +0100
+++ b/make/autoconf/hotspot.m4	Mon Oct 01 09:56:45 2018 +0100
@@ -351,6 +351,11 @@
     AC_MSG_RESULT([no])
   fi
 
+  # Disable unsupported GCs for Zero
+  if HOTSPOT_CHECK_JVM_VARIANT(zero); then
+    DISABLED_JVM_FEATURES="$DISABLED_JVM_FEATURES epsilongc g1gc zgc"
+  fi
+
   # Turn on additional features based on other parts of configure
   if test "x$INCLUDE_DTRACE" = "xtrue"; then
     JVM_FEATURES="$JVM_FEATURES dtrace"
--- a/make/conf/jib-profiles.js	Wed Sep 26 18:11:00 2018 +0100
+++ b/make/conf/jib-profiles.js	Mon Oct 01 09:56:45 2018 +0100
@@ -840,7 +840,7 @@
         linux_x64: "gcc7.3.0-OEL6.4+1.0",
         macosx_x64: "Xcode9.4-MacOSX10.13+1.0",
         solaris_x64: "SS12u4-Solaris11u1+1.0",
-        solaris_sparcv9: "SS12u4-Solaris11u1+1.1",
+        solaris_sparcv9: "SS12u6-Solaris11u3+1.0",
         windows_x64: "VS2017-15.5.5+1.0",
         linux_aarch64: (input.profile != null && input.profile.indexOf("arm64") >= 0
                     ? "gcc-linaro-aarch64-linux-gnu-4.8-2013.11_linux+1.0"
--- a/make/devkit/createSolarisDevkit12.6.sh	Wed Sep 26 18:11:00 2018 +0100
+++ b/make/devkit/createSolarisDevkit12.6.sh	Mon Oct 01 09:56:45 2018 +0100
@@ -34,18 +34,19 @@
 # install in a separate temporary image.
 #
 # The Solaris Studio installation must contain at least these packages:
-# developer/developerstudio-126/backend               12.6-1.0.0.0               i--
-# developer/developerstudio-126/c++                   12.6-1.0.0.0               i--
-# developer/developerstudio-126/cc                    12.6-1.0.0.0               i--
-# developer/developerstudio-126/dbx (solarisstudio)   12.6-1.0.0.0               i--
-# developer/developerstudio-126/library/c++-libs      12.6-1.0.0.0               i--
-# developer/developerstudio-126/library/math-libs     12.6-1.0.0.0               i--
-# developer/developerstudio-126/library/c-libs        12.6-1.0.0.0               i--
-# developer/developerstudio-126/library/studio-gccrt  12.6-1.0.0.0               i--
-# developer/developerstudio-126/studio-common         12.6-1.0.0.0               i--
-# developer/developerstudio-126/studio-ja             12.6-1.0.0.0               i--
-# developer/developerstudio-126/studio-legal          12.6-1.0.0.0               i--
-# developer/developerstudio-126/studio-zhCN           12.6-1.0.0.0               i--
+#developer/developerstudio-126/backend                12.6-1.0.0.1
+#developer/developerstudio-126/c++                    12.6-1.0.2.0
+#developer/developerstudio-126/cc                     12.6-1.0.1.0
+#developer/developerstudio-126/dbx                    12.6-1.0.0.1
+#developer/developerstudio-126/library/c++-libs       12.6-1.0.2.0
+#developer/developerstudio-126/library/c-libs         12.6-1.0.0.1
+#developer/developerstudio-126/library/f90-libs       12.6-1.0.0.1
+#developer/developerstudio-126/library/math-libs      12.6-1.0.0.1
+#developer/developerstudio-126/library/studio-gccrt   12.6-1.0.0.1
+#developer/developerstudio-126/studio-common          12.6-1.0.0.1
+#developer/developerstudio-126/studio-ja              12.6-1.0.0.1
+#developer/developerstudio-126/studio-legal           12.6-1.0.0.1
+#developer/developerstudio-126/studio-zhCN            12.6-1.0.0.1
 #
 # erik.joelsson@oracle.com
 
@@ -93,7 +94,7 @@
   pkg -R $INSTALL_ROOT set-publisher -P -g ${PUBLISHER_URI} solaris
   sudo pkg -R $INSTALL_ROOT install --accept entire@$SOLARIS_ENTIRE_VERSION \
       system/install developer/gnu-binutils system/library/mmheap system/picl \
-      developer/assembler
+      developer/assembler system/library/freetype-2
 else
   echo "Skipping installing packages"
 fi
--- a/make/lib/CoreLibraries.gmk	Wed Sep 26 18:11:00 2018 +0100
+++ b/make/lib/CoreLibraries.gmk	Mon Oct 01 09:56:45 2018 +0100
@@ -244,7 +244,7 @@
       EXCLUDE_FILES := $(LIBJLI_EXCLUDE_FILES), \
       EXTRA_FILES := $(LIBJLI_EXTRA_FILES), \
       OPTIMIZATION := HIGH, \
-      CFLAGS := $(STATIC_LIBRARY_FLAGS) $(LIBJLI_CFLAGS_JDKLIB) $(LIBJLI_CFLAGS) \
+      CFLAGS := $(STATIC_LIBRARY_FLAGS) $(CFLAGS_JDKLIB) $(LIBJLI_CFLAGS) \
           $(addprefix -I, $(LIBJLI_SRC_DIRS)), \
       ARFLAGS := $(ARFLAGS), \
       OBJECT_DIR := $(SUPPORT_OUTPUTDIR)/native/$(MODULE)/libjli_static))
--- a/src/demo/share/jfc/J2Ddemo/java2d/DemoInstVarsAccessor.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/demo/share/jfc/J2Ddemo/java2d/DemoInstVarsAccessor.java	Mon Oct 01 09:56:45 2018 +0100
@@ -1,3 +1,34 @@
+/*
+ *
+ * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ *   - Redistributions of source code must retain the above copyright
+ *     notice, this list of conditions and the following disclaimer.
+ *
+ *   - Redistributions in binary form must reproduce the above copyright
+ *     notice, this list of conditions and the following disclaimer in the
+ *     documentation and/or other materials provided with the distribution.
+ *
+ *   - Neither the name of Oracle nor the names of its
+ *     contributors may be used to endorse or promote products derived
+ *     from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
+ * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
 package java2d;
 
 import java.awt.Color;
--- a/src/demo/share/jfc/J2Ddemo/java2d/DemoInstVarsAccessorImplBase.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/demo/share/jfc/J2Ddemo/java2d/DemoInstVarsAccessorImplBase.java	Mon Oct 01 09:56:45 2018 +0100
@@ -1,3 +1,34 @@
+/*
+ *
+ * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ *   - Redistributions of source code must retain the above copyright
+ *     notice, this list of conditions and the following disclaimer.
+ *
+ *   - Redistributions in binary form must reproduce the above copyright
+ *     notice, this list of conditions and the following disclaimer in the
+ *     documentation and/or other materials provided with the distribution.
+ *
+ *   - Neither the name of Oracle nor the names of its
+ *     contributors may be used to endorse or promote products derived
+ *     from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
+ * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
 package java2d;
 
 import java.awt.Color;
--- a/src/hotspot/cpu/arm/c1_LIRGenerator_arm.cpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/hotspot/cpu/arm/c1_LIRGenerator_arm.cpp	Mon Oct 01 09:56:45 2018 +0100
@@ -870,8 +870,8 @@
     case doubleTag:  do_ArithmeticOp_FPU(x);  return;
     case longTag:    do_ArithmeticOp_Long(x); return;
     case intTag:     do_ArithmeticOp_Int(x);  return;
+    default:         ShouldNotReachHere();    return;
   }
-  ShouldNotReachHere();
 }
 
 
--- a/src/hotspot/cpu/arm/templateTable_arm.cpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/hotspot/cpu/arm/templateTable_arm.cpp	Mon Oct 01 09:56:45 2018 +0100
@@ -2996,6 +2996,7 @@
   switch (code) {
   case Bytecodes::_nofast_getfield: code = Bytecodes::_getfield; break;
   case Bytecodes::_nofast_putfield: code = Bytecodes::_putfield; break;
+  default: break;
   }
 
   assert(byte_no == f1_byte || byte_no == f2_byte, "byte_no out of range");
--- a/src/hotspot/cpu/x86/c1_LIRAssembler_x86.cpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/hotspot/cpu/x86/c1_LIRAssembler_x86.cpp	Mon Oct 01 09:56:45 2018 +0100
@@ -2403,8 +2403,9 @@
           if (UseAVX > 2 && !VM_Version::supports_avx512vl()) {
             assert(tmp->is_valid(), "need temporary");
             __ vpandn(dest->as_xmm_double_reg(), tmp->as_xmm_double_reg(), value->as_xmm_double_reg(), 2);
-          } else {
+          } else
 #endif
+          {
             if (dest->as_xmm_double_reg() != value->as_xmm_double_reg()) {
               __ movdbl(dest->as_xmm_double_reg(), value->as_xmm_double_reg());
             }
--- a/src/hotspot/cpu/x86/jniFastGetField_x86_32.cpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/hotspot/cpu/x86/jniFastGetField_x86_32.cpp	Mon Oct 01 09:56:45 2018 +0100
@@ -131,7 +131,8 @@
     case T_BYTE:    slow_case_addr = jni_GetByteField_addr();    break;
     case T_CHAR:    slow_case_addr = jni_GetCharField_addr();    break;
     case T_SHORT:   slow_case_addr = jni_GetShortField_addr();   break;
-    case T_INT:     slow_case_addr = jni_GetIntField_addr();
+    case T_INT:     slow_case_addr = jni_GetIntField_addr();     break;
+    default:        ShouldNotReachHere();
   }
   // tail call
   __ jump (ExternalAddress(slow_case_addr));
--- a/src/hotspot/cpu/x86/stubGenerator_x86_32.cpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/hotspot/cpu/x86/stubGenerator_x86_32.cpp	Mon Oct 01 09:56:45 2018 +0100
@@ -87,8 +87,8 @@
     case T_INT:     inc_counter_np(SharedRuntime::_jint_array_copy_ctr); return;
     case T_LONG:    inc_counter_np(SharedRuntime::_jlong_array_copy_ctr); return;
     case T_OBJECT:  inc_counter_np(SharedRuntime::_oop_array_copy_ctr); return;
+    default:        ShouldNotReachHere();
     }
-    ShouldNotReachHere();
 #endif //PRODUCT
   }
 
--- a/src/hotspot/os/linux/os_linux.cpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/hotspot/os/linux/os_linux.cpp	Mon Oct 01 09:56:45 2018 +0100
@@ -1877,12 +1877,16 @@
   return (void*)::dlopen(NULL, RTLD_LAZY);
 }
 
-static bool _print_ascii_file(const char* filename, outputStream* st) {
+static bool _print_ascii_file(const char* filename, outputStream* st, const char* hdr = NULL) {
   int fd = ::open(filename, O_RDONLY);
   if (fd == -1) {
     return false;
   }
 
+  if (hdr != NULL) {
+    st->print_cr("%s", hdr);
+  }
+
   char buf[33];
   int bytes;
   buf[32] = '\0';
@@ -1975,6 +1979,8 @@
 
   os::Linux::print_proc_sys_info(st);
 
+  os::Linux::print_ld_preload_file(st);
+
   os::Linux::print_container_info(st);
 }
 
@@ -2133,6 +2139,11 @@
   st->cr();
 }
 
+void os::Linux::print_ld_preload_file(outputStream* st) {
+  _print_ascii_file("/etc/ld.so.preload", st, "\n/etc/ld.so.preload:");
+  st->cr();
+}
+
 void os::Linux::print_container_info(outputStream* st) {
   if (!OSContainer::is_containerized()) {
     return;
--- a/src/hotspot/os/linux/os_linux.hpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/hotspot/os/linux/os_linux.hpp	Mon Oct 01 09:56:45 2018 +0100
@@ -114,6 +114,7 @@
   static void print_distro_info(outputStream* st);
   static void print_libversion_info(outputStream* st);
   static void print_proc_sys_info(outputStream* st);
+  static void print_ld_preload_file(outputStream* st);
 
  public:
   static bool _stack_is_executable;
--- a/src/hotspot/share/classfile/classLoaderData.cpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/hotspot/share/classfile/classLoaderData.cpp	Mon Oct 01 09:56:45 2018 +0100
@@ -47,11 +47,10 @@
 // the singleton class the_null_class_loader_data().
 
 #include "precompiled.hpp"
-#include "classfile/classLoaderData.hpp"
 #include "classfile/classLoaderData.inline.hpp"
+#include "classfile/classLoaderDataGraph.inline.hpp"
 #include "classfile/dictionary.hpp"
 #include "classfile/javaClasses.hpp"
-#include "classfile/metadataOnStackMark.hpp"
 #include "classfile/moduleEntry.hpp"
 #include "classfile/packageEntry.hpp"
 #include "classfile/symbolTable.hpp"
@@ -60,9 +59,7 @@
 #include "logging/logStream.hpp"
 #include "memory/allocation.inline.hpp"
 #include "memory/metadataFactory.hpp"
-#include "memory/metaspaceShared.hpp"
 #include "memory/resourceArea.hpp"
-#include "memory/universe.hpp"
 #include "oops/access.inline.hpp"
 #include "oops/oop.inline.hpp"
 #include "oops/oopHandle.inline.hpp"
@@ -72,14 +69,10 @@
 #include "runtime/mutex.hpp"
 #include "runtime/orderAccess.hpp"
 #include "runtime/safepoint.hpp"
-#include "runtime/safepointVerifiers.hpp"
 #include "utilities/growableArray.hpp"
 #include "utilities/macros.hpp"
 #include "utilities/ostream.hpp"
 
-volatile size_t ClassLoaderDataGraph::_num_array_classes = 0;
-volatile size_t ClassLoaderDataGraph::_num_instance_classes = 0;
-
 ClassLoaderData * ClassLoaderData::_the_null_class_loader_data = NULL;
 
 void ClassLoaderData::init_null_class_loader_data() {
@@ -345,6 +338,11 @@
   for (Klass* k = OrderAccess::load_acquire(&_klasses); k != NULL; k = k->next_link()) {
     // Do not filter ArrayKlass oops here...
     if (k->is_array_klass() || (k->is_instance_klass() && InstanceKlass::cast(k)->is_loaded())) {
+#ifdef ASSERT
+      oop m = k->java_mirror();
+      assert(m != NULL, "NULL mirror");
+      assert(m->is_a(SystemDictionary::Class_klass()), "invalid mirror");
+#endif
       klass_closure->do_klass(k);
     }
   }
@@ -444,13 +442,6 @@
   }
 }
 
-
-void ClassLoaderDataGraph::clear_claimed_marks() {
-  for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
-    cld->clear_claimed();
-  }
-}
-
 void ClassLoaderData::add_class(Klass* k, bool publicize /* true */) {
   {
     MutexLockerEx ml(metaspace_lock(), Mutex::_no_safepoint_check_flag);
@@ -478,78 +469,6 @@
   }
 }
 
-// Class iterator used by the compiler.  It gets some number of classes at
-// a safepoint to decay invocation counters on the methods.
-class ClassLoaderDataGraphKlassIteratorStatic {
-  ClassLoaderData* _current_loader_data;
-  Klass*           _current_class_entry;
- public:
-
-  ClassLoaderDataGraphKlassIteratorStatic() : _current_loader_data(NULL), _current_class_entry(NULL) {}
-
-  InstanceKlass* try_get_next_class() {
-    assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
-    size_t max_classes = ClassLoaderDataGraph::num_instance_classes();
-    assert(max_classes > 0, "should not be called with no instance classes");
-    for (size_t i = 0; i < max_classes; ) {
-
-      if (_current_class_entry != NULL) {
-        Klass* k = _current_class_entry;
-        _current_class_entry = _current_class_entry->next_link();
-
-        if (k->is_instance_klass()) {
-          InstanceKlass* ik = InstanceKlass::cast(k);
-          i++;  // count all instance classes found
-          // Not yet loaded classes are counted in max_classes
-          // but only return loaded classes.
-          if (ik->is_loaded()) {
-            return ik;
-          }
-        }
-      } else {
-        // Go to next CLD
-        if (_current_loader_data != NULL) {
-          _current_loader_data = _current_loader_data->next();
-        }
-        // Start at the beginning
-        if (_current_loader_data == NULL) {
-          _current_loader_data = ClassLoaderDataGraph::_head;
-        }
-
-        _current_class_entry = _current_loader_data->klasses();
-      }
-    }
-    // Should never be reached unless all instance classes have failed or are not fully loaded.
-    // Caller handles NULL.
-    return NULL;
-  }
-
-  // If the current class for the static iterator is a class being unloaded or
-  // deallocated, adjust the current class.
-  void adjust_saved_class(ClassLoaderData* cld) {
-    if (_current_loader_data == cld) {
-      _current_loader_data = cld->next();
-      if (_current_loader_data != NULL) {
-        _current_class_entry = _current_loader_data->klasses();
-      }  // else try_get_next_class will start at the head
-    }
-  }
-
-  void adjust_saved_class(Klass* klass) {
-    if (_current_class_entry == klass) {
-      _current_class_entry = klass->next_link();
-    }
-  }
-};
-
-static ClassLoaderDataGraphKlassIteratorStatic static_klass_iterator;
-
-InstanceKlass* ClassLoaderDataGraph::try_get_next_class() {
-  assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
-  return static_klass_iterator.try_get_next_class();
-}
-
-
 void ClassLoaderData::initialize_holder(Handle loader_or_mirror) {
   if (loader_or_mirror() != NULL) {
     assert(_holder.is_null(), "never replace holders");
@@ -563,7 +482,7 @@
   assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
 
   // Adjust global class iterator.
-  static_klass_iterator.adjust_saved_class(scratch_class);
+  ClassLoaderDataGraph::adjust_saved_class(scratch_class);
 
   Klass* prev = NULL;
   for (Klass* k = _klasses; k != NULL; k = k->next_link()) {
@@ -605,12 +524,13 @@
   // if they are not already on the _klasses list.
   free_deallocate_list_C_heap_structures();
 
-  // Tell serviceability tools these classes are unloading
+  // Clean up class dependencies and tell serviceability tools
+  // these classes are unloading.  Must be called
   // after erroneous classes are released.
-  classes_do(InstanceKlass::notify_unload_class);
+  classes_do(InstanceKlass::unload_class);
 
   // Clean up global class iterator for compiler
-  static_klass_iterator.adjust_saved_class(this);
+  ClassLoaderDataGraph::adjust_saved_class(this);
 }
 
 ModuleEntryTable* ClassLoaderData::modules() {
@@ -913,41 +833,6 @@
   }
 }
 
-void ClassLoaderDataGraph::clean_deallocate_lists(bool walk_previous_versions) {
-  assert(SafepointSynchronize::is_at_safepoint(), "must only be called at safepoint");
-  uint loaders_processed = 0;
-  for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
-    // is_alive check will be necessary for concurrent class unloading.
-    if (cld->is_alive()) {
-      // clean metaspace
-      if (walk_previous_versions) {
-        cld->classes_do(InstanceKlass::purge_previous_versions);
-      }
-      cld->free_deallocate_list();
-      loaders_processed++;
-    }
-  }
-  log_debug(class, loader, data)("clean_deallocate_lists: loaders processed %u %s",
-                                 loaders_processed, walk_previous_versions ? "walk_previous_versions" : "");
-}
-
-void ClassLoaderDataGraph::walk_metadata_and_clean_metaspaces() {
-  assert(SafepointSynchronize::is_at_safepoint(), "must only be called at safepoint");
-
-  _should_clean_deallocate_lists = false; // assume everything gets cleaned
-
-  // Mark metadata seen on the stack so we can delete unreferenced entries.
-  // Walk all metadata, including the expensive code cache walk, only for class redefinition.
-  // The MetadataOnStackMark walk during redefinition saves previous versions if it finds old methods
-  // on the stack or in the code cache, so we only have to repeat the full walk if
-  // they were found at that time.
-  // TODO: have redefinition clean old methods out of the code cache.  They still exist in some places.
-  bool walk_all_metadata = InstanceKlass::has_previous_versions_and_reset();
-
-  MetadataOnStackMark md_on_stack(walk_all_metadata);
-  clean_deallocate_lists(walk_all_metadata);
-}
-
 // This is distinct from free_deallocate_list.  For class loader data that are
 // unloading, this frees the C heap memory for items on the list, and unlinks
 // scratch or error classes so that unloading events aren't triggered for these
@@ -1069,523 +954,3 @@
   }
   return false;
 }
-
-
-// GC root of class loader data created.
-ClassLoaderData* ClassLoaderDataGraph::_head = NULL;
-ClassLoaderData* ClassLoaderDataGraph::_unloading = NULL;
-ClassLoaderData* ClassLoaderDataGraph::_saved_unloading = NULL;
-ClassLoaderData* ClassLoaderDataGraph::_saved_head = NULL;
-
-bool ClassLoaderDataGraph::_should_purge = false;
-bool ClassLoaderDataGraph::_should_clean_deallocate_lists = false;
-bool ClassLoaderDataGraph::_safepoint_cleanup_needed = false;
-bool ClassLoaderDataGraph::_metaspace_oom = false;
-
-// Add a new class loader data node to the list.  Assign the newly created
-// ClassLoaderData into the java/lang/ClassLoader object as a hidden field
-ClassLoaderData* ClassLoaderDataGraph::add_to_graph(Handle loader, bool is_unsafe_anonymous) {
-
-  assert_lock_strong(ClassLoaderDataGraph_lock);
-
-  ClassLoaderData* cld;
-
-  // First check if another thread beat us to creating the CLD and installing
-  // it into the loader while we were waiting for the lock.
-  if (!is_unsafe_anonymous && loader.not_null()) {
-    cld = java_lang_ClassLoader::loader_data_acquire(loader());
-    if (cld != NULL) {
-      return cld;
-    }
-  }
-
-  // We mustn't GC until we've installed the ClassLoaderData in the Graph since the CLD
-  // contains oops in _handles that must be walked.  GC doesn't walk CLD from the
-  // loader oop in all collections, particularly young collections.
-  NoSafepointVerifier no_safepoints;
-
-  cld = new ClassLoaderData(loader, is_unsafe_anonymous);
-
-  // First install the new CLD to the Graph.
-  cld->set_next(_head);
-  _head = cld;
-
-  // Next associate with the class_loader.
-  if (!is_unsafe_anonymous) {
-    // Use OrderAccess, since readers need to get the loader_data only after
-    // it's added to the Graph
-    java_lang_ClassLoader::release_set_loader_data(loader(), cld);
-  }
-
-  // Lastly log, if requested
-  LogTarget(Trace, class, loader, data) lt;
-  if (lt.is_enabled()) {
-    ResourceMark rm;
-    LogStream ls(lt);
-    ls.print("create ");
-    cld->print_value_on(&ls);
-    ls.cr();
-  }
-  return cld;
-}
-
-ClassLoaderData* ClassLoaderDataGraph::add(Handle loader, bool is_unsafe_anonymous) {
-  MutexLocker ml(ClassLoaderDataGraph_lock);
-  ClassLoaderData* loader_data = add_to_graph(loader, is_unsafe_anonymous);
-  return loader_data;
-}
-
-void ClassLoaderDataGraph::cld_do(CLDClosure* cl) {
-  assert_locked_or_safepoint(ClassLoaderDataGraph_lock);
-  for (ClassLoaderData* cld = _head;  cld != NULL; cld = cld->_next) {
-    cl->do_cld(cld);
-  }
-}
-
-void ClassLoaderDataGraph::cld_unloading_do(CLDClosure* cl) {
-  assert_locked_or_safepoint(ClassLoaderDataGraph_lock);
-  // Only walk the head until any clds not purged from prior unloading
-  // (CMS doesn't purge right away).
-  for (ClassLoaderData* cld = _unloading; cld != _saved_unloading; cld = cld->next()) {
-    assert(cld->is_unloading(), "invariant");
-    cl->do_cld(cld);
-  }
-}
-
-void ClassLoaderDataGraph::roots_cld_do(CLDClosure* strong, CLDClosure* weak) {
-  assert_locked_or_safepoint(ClassLoaderDataGraph_lock);
-  for (ClassLoaderData* cld = _head;  cld != NULL; cld = cld->_next) {
-    CLDClosure* closure = cld->keep_alive() ? strong : weak;
-    if (closure != NULL) {
-      closure->do_cld(cld);
-    }
-  }
-}
-
-void ClassLoaderDataGraph::always_strong_cld_do(CLDClosure* cl) {
-  assert_locked_or_safepoint(ClassLoaderDataGraph_lock);
-  if (ClassUnloading) {
-    roots_cld_do(cl, NULL);
-  } else {
-    cld_do(cl);
-  }
-}
-
-// Closure for locking and iterating through classes.
-LockedClassesDo::LockedClassesDo(classes_do_func_t f) : _function(f) {
-  ClassLoaderDataGraph_lock->lock();
-}
-
-LockedClassesDo::LockedClassesDo() : _function(NULL) {
-  // callers provide their own do_klass
-  ClassLoaderDataGraph_lock->lock();
-}
-
-LockedClassesDo::~LockedClassesDo() { ClassLoaderDataGraph_lock->unlock(); }
-
-
-// Iterating over the CLDG needs to be locked because
-// unloading can remove entries concurrently soon.
-class ClassLoaderDataGraphIterator : public StackObj {
-  ClassLoaderData* _next;
-  HandleMark       _hm;  // clean up handles when this is done.
-  Handle           _holder;
-  Thread*          _thread;
-
-  void hold_next() {
-    if (_next != NULL) {
-      _holder = Handle(_thread, _next->holder_phantom());
-    }
-  }
-public:
-  ClassLoaderDataGraphIterator() : _next(ClassLoaderDataGraph::_head) {
-    _thread = Thread::current();
-    assert_locked_or_safepoint(ClassLoaderDataGraph_lock);
-    hold_next();
-  }
-
-  bool repeat() const {
-    return _next != NULL;
-  }
-
-  ClassLoaderData* get_next() {
-    ClassLoaderData* next = _next;
-    if (_next != NULL) {
-      _next = _next->next();
-      hold_next();
-    }
-    return next;
-  }
-};
-
-// These functions assume that the caller has locked the ClassLoaderDataGraph_lock
-// if they are not calling the function from a safepoint.
-void ClassLoaderDataGraph::classes_do(KlassClosure* klass_closure) {
-  ClassLoaderDataGraphIterator iter;
-  while (iter.repeat()) {
-    ClassLoaderData* cld = iter.get_next();
-    cld->classes_do(klass_closure);
-  }
-}
-
-void ClassLoaderDataGraph::classes_do(void f(Klass* const)) {
-  ClassLoaderDataGraphIterator iter;
-  while (iter.repeat()) {
-    ClassLoaderData* cld = iter.get_next();
-    cld->classes_do(f);
-  }
-}
-
-void ClassLoaderDataGraph::methods_do(void f(Method*)) {
-  ClassLoaderDataGraphIterator iter;
-  while (iter.repeat()) {
-    ClassLoaderData* cld = iter.get_next();
-    cld->methods_do(f);
-  }
-}
-
-void ClassLoaderDataGraph::modules_do(void f(ModuleEntry*)) {
-  assert_locked_or_safepoint(Module_lock);
-  ClassLoaderDataGraphIterator iter;
-  while (iter.repeat()) {
-    ClassLoaderData* cld = iter.get_next();
-    cld->modules_do(f);
-  }
-}
-
-void ClassLoaderDataGraph::modules_unloading_do(void f(ModuleEntry*)) {
-  assert_locked_or_safepoint(ClassLoaderDataGraph_lock);
-  // Only walk the head until any clds not purged from prior unloading
-  // (CMS doesn't purge right away).
-  for (ClassLoaderData* cld = _unloading; cld != _saved_unloading; cld = cld->next()) {
-    assert(cld->is_unloading(), "invariant");
-    cld->modules_do(f);
-  }
-}
-
-void ClassLoaderDataGraph::packages_do(void f(PackageEntry*)) {
-  assert_locked_or_safepoint(Module_lock);
-  ClassLoaderDataGraphIterator iter;
-  while (iter.repeat()) {
-    ClassLoaderData* cld = iter.get_next();
-    cld->packages_do(f);
-  }
-}
-
-void ClassLoaderDataGraph::packages_unloading_do(void f(PackageEntry*)) {
-  assert_locked_or_safepoint(ClassLoaderDataGraph_lock);
-  // Only walk the head until any clds not purged from prior unloading
-  // (CMS doesn't purge right away).
-  for (ClassLoaderData* cld = _unloading; cld != _saved_unloading; cld = cld->next()) {
-    assert(cld->is_unloading(), "invariant");
-    cld->packages_do(f);
-  }
-}
-
-void ClassLoaderDataGraph::loaded_classes_do(KlassClosure* klass_closure) {
-  ClassLoaderDataGraphIterator iter;
-  while (iter.repeat()) {
-    ClassLoaderData* cld = iter.get_next();
-    cld->loaded_classes_do(klass_closure);
-  }
-}
-
-// This case can block but cannot do unloading (called from CDS)
-void ClassLoaderDataGraph::unlocked_loaded_classes_do(KlassClosure* klass_closure) {
-  for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
-    cld->loaded_classes_do(klass_closure);
-  }
-}
-
-
-void ClassLoaderDataGraph::classes_unloading_do(void f(Klass* const)) {
-  assert_locked_or_safepoint(ClassLoaderDataGraph_lock);
-  // Only walk the head until any clds not purged from prior unloading
-  // (CMS doesn't purge right away).
-  for (ClassLoaderData* cld = _unloading; cld != _saved_unloading; cld = cld->next()) {
-    assert(cld->is_unloading(), "invariant");
-    cld->classes_do(f);
-  }
-}
-
-#define FOR_ALL_DICTIONARY(X)   ClassLoaderDataGraphIterator iter; \
-                                ClassLoaderData* X; \
-                                while ((X = iter.get_next()) != NULL) \
-                                  if (X->dictionary() != NULL)
-
-// Walk classes in the loaded class dictionaries in various forms.
-// Only walks the classes defined in this class loader.
-void ClassLoaderDataGraph::dictionary_classes_do(void f(InstanceKlass*)) {
-  FOR_ALL_DICTIONARY(cld) {
-    cld->dictionary()->classes_do(f);
-  }
-}
-
-// Only walks the classes defined in this class loader.
-void ClassLoaderDataGraph::dictionary_classes_do(void f(InstanceKlass*, TRAPS), TRAPS) {
-  FOR_ALL_DICTIONARY(cld) {
-    cld->dictionary()->classes_do(f, CHECK);
-  }
-}
-
-void ClassLoaderDataGraph::verify_dictionary() {
-  FOR_ALL_DICTIONARY(cld) {
-    cld->dictionary()->verify();
-  }
-}
-
-void ClassLoaderDataGraph::print_dictionary(outputStream* st) {
-  FOR_ALL_DICTIONARY(cld) {
-    st->print("Dictionary for ");
-    cld->print_value_on(st);
-    st->cr();
-    cld->dictionary()->print_on(st);
-    st->cr();
-  }
-}
-
-void ClassLoaderDataGraph::print_dictionary_statistics(outputStream* st) {
-  FOR_ALL_DICTIONARY(cld) {
-    ResourceMark rm;
-    stringStream tempst;
-    tempst.print("System Dictionary for %s class loader", cld->loader_name_and_id());
-    cld->dictionary()->print_table_statistics(st, tempst.as_string());
-  }
-}
-
-GrowableArray<ClassLoaderData*>* ClassLoaderDataGraph::new_clds() {
-  assert_locked_or_safepoint(ClassLoaderDataGraph_lock);
-  assert(_head == NULL || _saved_head != NULL, "remember_new_clds(true) not called?");
-
-  GrowableArray<ClassLoaderData*>* array = new GrowableArray<ClassLoaderData*>();
-
-  // The CLDs in [_head, _saved_head] were all added during last call to remember_new_clds(true);
-  ClassLoaderData* curr = _head;
-  while (curr != _saved_head) {
-    if (!curr->claimed()) {
-      array->push(curr);
-      LogTarget(Debug, class, loader, data) lt;
-      if (lt.is_enabled()) {
-        LogStream ls(lt);
-        ls.print("found new CLD: ");
-        curr->print_value_on(&ls);
-        ls.cr();
-      }
-    }
-
-    curr = curr->_next;
-  }
-
-  return array;
-}
-
-#ifndef PRODUCT
-bool ClassLoaderDataGraph::contains_loader_data(ClassLoaderData* loader_data) {
-  assert_locked_or_safepoint(ClassLoaderDataGraph_lock);
-  for (ClassLoaderData* data = _head; data != NULL; data = data->next()) {
-    if (loader_data == data) {
-      return true;
-    }
-  }
-
-  return false;
-}
-#endif // PRODUCT
-
-// Move class loader data from main list to the unloaded list for unloading
-// and deallocation later.
-bool ClassLoaderDataGraph::do_unloading(bool do_cleaning) {
-  assert_locked_or_safepoint(ClassLoaderDataGraph_lock);
-
-  // Indicate whether safepoint cleanup is needed.
-  _safepoint_cleanup_needed |= do_cleaning;
-
-  ClassLoaderData* data = _head;
-  ClassLoaderData* prev = NULL;
-  bool seen_dead_loader = false;
-  uint loaders_processed = 0;
-  uint loaders_removed = 0;
-
-  // Save previous _unloading pointer for CMS which may add to unloading list before
-  // purging and we don't want to rewalk the previously unloaded class loader data.
-  _saved_unloading = _unloading;
-
-  data = _head;
-  while (data != NULL) {
-    if (data->is_alive()) {
-      prev = data;
-      data = data->next();
-      loaders_processed++;
-      continue;
-    }
-    seen_dead_loader = true;
-    loaders_removed++;
-    ClassLoaderData* dead = data;
-    dead->unload();
-    data = data->next();
-    // Remove from loader list.
-    // This class loader data will no longer be found
-    // in the ClassLoaderDataGraph.
-    if (prev != NULL) {
-      prev->set_next(data);
-    } else {
-      assert(dead == _head, "sanity check");
-      _head = data;
-    }
-    dead->set_next(_unloading);
-    _unloading = dead;
-  }
-
-  log_debug(class, loader, data)("do_unloading: loaders processed %u, loaders removed %u", loaders_processed, loaders_removed);
-
-  return seen_dead_loader;
-}
-
-// There's at least one dead class loader.  Purge refererences of healthy module
-// reads lists and package export lists to modules belonging to dead loaders.
-void ClassLoaderDataGraph::clean_module_and_package_info() {
-  assert_locked_or_safepoint(ClassLoaderDataGraph_lock);
-
-  ClassLoaderData* data = _head;
-  while (data != NULL) {
-    // Remove entries in the dictionary of live class loader that have
-    // initiated loading classes in a dead class loader.
-    if (data->dictionary() != NULL) {
-      data->dictionary()->do_unloading();
-    }
-    // Walk a ModuleEntry's reads, and a PackageEntry's exports
-    // lists to determine if there are modules on those lists that are now
-    // dead and should be removed.  A module's life cycle is equivalent
-    // to its defining class loader's life cycle.  Since a module is
-    // considered dead if its class loader is dead, these walks must
-    // occur after each class loader's aliveness is determined.
-    if (data->packages() != NULL) {
-      data->packages()->purge_all_package_exports();
-    }
-    if (data->modules_defined()) {
-      data->modules()->purge_all_module_reads();
-    }
-    data = data->next();
-  }
-}
-
-void ClassLoaderDataGraph::purge() {
-  assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint!");
-  ClassLoaderData* list = _unloading;
-  _unloading = NULL;
-  ClassLoaderData* next = list;
-  bool classes_unloaded = false;
-  while (next != NULL) {
-    ClassLoaderData* purge_me = next;
-    next = purge_me->next();
-    delete purge_me;
-    classes_unloaded = true;
-  }
-  if (classes_unloaded) {
-    Metaspace::purge();
-    set_metaspace_oom(false);
-  }
-}
-
-int ClassLoaderDataGraph::resize_if_needed() {
-  assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint!");
-  int resized = 0;
-  if (Dictionary::does_any_dictionary_needs_resizing()) {
-    FOR_ALL_DICTIONARY(cld) {
-      if (cld->dictionary()->resize_if_needed()) {
-        resized++;
-      }
-    }
-  }
-  return resized;
-}
-
-ClassLoaderDataGraphKlassIteratorAtomic::ClassLoaderDataGraphKlassIteratorAtomic()
-    : _next_klass(NULL) {
-  assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint!");
-  ClassLoaderData* cld = ClassLoaderDataGraph::_head;
-  Klass* klass = NULL;
-
-  // Find the first klass in the CLDG.
-  while (cld != NULL) {
-    assert_locked_or_safepoint(cld->metaspace_lock());
-    klass = cld->_klasses;
-    if (klass != NULL) {
-      _next_klass = klass;
-      return;
-    }
-    cld = cld->next();
-  }
-}
-
-Klass* ClassLoaderDataGraphKlassIteratorAtomic::next_klass_in_cldg(Klass* klass) {
-  Klass* next = klass->next_link();
-  if (next != NULL) {
-    return next;
-  }
-
-  // No more klasses in the current CLD. Time to find a new CLD.
-  ClassLoaderData* cld = klass->class_loader_data();
-  assert_locked_or_safepoint(cld->metaspace_lock());
-  while (next == NULL) {
-    cld = cld->next();
-    if (cld == NULL) {
-      break;
-    }
-    next = cld->_klasses;
-  }
-
-  return next;
-}
-
-Klass* ClassLoaderDataGraphKlassIteratorAtomic::next_klass() {
-  Klass* head = _next_klass;
-
-  while (head != NULL) {
-    Klass* next = next_klass_in_cldg(head);
-
-    Klass* old_head = Atomic::cmpxchg(next, &_next_klass, head);
-
-    if (old_head == head) {
-      return head; // Won the CAS.
-    }
-
-    head = old_head;
-  }
-
-  // Nothing more for the iterator to hand out.
-  assert(head == NULL, "head is " PTR_FORMAT ", expected not null:", p2i(head));
-  return NULL;
-}
-
-ClassLoaderDataGraphMetaspaceIterator::ClassLoaderDataGraphMetaspaceIterator() {
-  assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint!");
-  _data = ClassLoaderDataGraph::_head;
-}
-
-ClassLoaderDataGraphMetaspaceIterator::~ClassLoaderDataGraphMetaspaceIterator() {}
-
-#ifndef PRODUCT
-// callable from debugger
-extern "C" int print_loader_data_graph() {
-  ResourceMark rm;
-  ClassLoaderDataGraph::print_on(tty);
-  return 0;
-}
-
-void ClassLoaderDataGraph::verify() {
-  ClassLoaderDataGraphIterator iter;
-  while (iter.repeat()) {
-    ClassLoaderData* cld = iter.get_next();
-    cld->verify();
-  }
-}
-
-void ClassLoaderDataGraph::print_on(outputStream * const out) {
-  ClassLoaderDataGraphIterator iter;
-  while (iter.repeat()) {
-    ClassLoaderData* cld = iter.get_next();
-    cld->print_on(out);
-  }
-}
-#endif // PRODUCT
--- a/src/hotspot/share/classfile/classLoaderData.hpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/hotspot/share/classfile/classLoaderData.hpp	Mon Oct 01 09:56:45 2018 +0100
@@ -53,9 +53,8 @@
 // ClassLoaderData are stored in the runtime representation of classes,
 // and provides iterators for root tracing and other GC operations.
 
-class ClassLoaderData;
+class ClassLoaderDataGraph;
 class JNIMethodBlock;
-class Metadebug;
 class ModuleEntry;
 class PackageEntry;
 class ModuleEntryTable;
@@ -63,136 +62,6 @@
 class DictionaryEntry;
 class Dictionary;
 
-// GC root for walking class loader data created
-
-class ClassLoaderDataGraph : public AllStatic {
-  friend class ClassLoaderData;
-  friend class ClassLoaderDataGraphMetaspaceIterator;
-  friend class ClassLoaderDataGraphKlassIteratorAtomic;
-  friend class ClassLoaderDataGraphKlassIteratorStatic;
-  friend class ClassLoaderDataGraphIterator;
-  friend class VMStructs;
- private:
-  // All CLDs (except the null CLD) can be reached by walking _head->_next->...
-  static ClassLoaderData* _head;
-  static ClassLoaderData* _unloading;
-  // CMS support.
-  static ClassLoaderData* _saved_head;
-  static ClassLoaderData* _saved_unloading;
-  static bool _should_purge;
-
-  // Set if there's anything to purge in the deallocate lists or previous versions
-  // during a safepoint after class unloading in a full GC.
-  static bool _should_clean_deallocate_lists;
-  static bool _safepoint_cleanup_needed;
-
-  // OOM has been seen in metaspace allocation. Used to prevent some
-  // allocations until class unloading
-  static bool _metaspace_oom;
-
-  static volatile size_t  _num_instance_classes;
-  static volatile size_t  _num_array_classes;
-
-  static ClassLoaderData* add_to_graph(Handle class_loader, bool is_unsafe_anonymous);
-  static ClassLoaderData* add(Handle class_loader, bool is_unsafe_anonymous);
-
- public:
-  static ClassLoaderData* find_or_create(Handle class_loader);
-  static void clean_module_and_package_info();
-  static void purge();
-  static void clear_claimed_marks();
-  // Iteration through CLDG inside a safepoint; GC support
-  static void cld_do(CLDClosure* cl);
-  static void cld_unloading_do(CLDClosure* cl);
-  static void roots_cld_do(CLDClosure* strong, CLDClosure* weak);
-  static void always_strong_cld_do(CLDClosure* cl);
-  // klass do
-  // Walking classes through the ClassLoaderDataGraph include array classes.  It also includes
-  // classes that are allocated but not loaded, classes that have errors, and scratch classes
-  // for redefinition.  These classes are removed during the next class unloading.
-  // Walking the ClassLoaderDataGraph also includes unsafe anonymous classes.
-  static void classes_do(KlassClosure* klass_closure);
-  static void classes_do(void f(Klass* const));
-  static void methods_do(void f(Method*));
-  static void modules_do(void f(ModuleEntry*));
-  static void modules_unloading_do(void f(ModuleEntry*));
-  static void packages_do(void f(PackageEntry*));
-  static void packages_unloading_do(void f(PackageEntry*));
-  static void loaded_classes_do(KlassClosure* klass_closure);
-  static void unlocked_loaded_classes_do(KlassClosure* klass_closure);
-  static void classes_unloading_do(void f(Klass* const));
-  static bool do_unloading(bool do_cleaning);
-
-  // Expose state to avoid logging overhead in safepoint cleanup tasks.
-  static inline bool should_clean_metaspaces_and_reset();
-  static void set_should_clean_deallocate_lists() { _should_clean_deallocate_lists = true; }
-  static void clean_deallocate_lists(bool purge_previous_versions);
-  static void walk_metadata_and_clean_metaspaces();
-
-  // dictionary do
-  // Iterate over all klasses in dictionary, but
-  // just the classes from defining class loaders.
-  static void dictionary_classes_do(void f(InstanceKlass*));
-  // Added for initialize_itable_for_klass to handle exceptions.
-  static void dictionary_classes_do(void f(InstanceKlass*, TRAPS), TRAPS);
-
-  // VM_CounterDecay iteration support
-  static InstanceKlass* try_get_next_class();
-
-  static void verify_dictionary();
-  static void print_dictionary(outputStream* st);
-  static void print_dictionary_statistics(outputStream* st);
-
-  // CMS support.
-  static void remember_new_clds(bool remember) { _saved_head = (remember ? _head : NULL); }
-  static GrowableArray<ClassLoaderData*>* new_clds();
-
-  static void set_should_purge(bool b) { _should_purge = b; }
-  static void purge_if_needed() {
-    // Only purge the CLDG for CMS if concurrent sweep is complete.
-    if (_should_purge) {
-      purge();
-      // reset for next time.
-      set_should_purge(false);
-    }
-  }
-
-  static int resize_if_needed();
-
-  static bool has_metaspace_oom()           { return _metaspace_oom; }
-  static void set_metaspace_oom(bool value) { _metaspace_oom = value; }
-
-  static void print_on(outputStream * const out) PRODUCT_RETURN;
-  static void print() { print_on(tty); }
-  static void verify();
-
-  // instance and array class counters
-  static inline size_t num_instance_classes();
-  static inline size_t num_array_classes();
-  static inline void inc_instance_classes(size_t count);
-  static inline void dec_instance_classes(size_t count);
-  static inline void inc_array_classes(size_t count);
-  static inline void dec_array_classes(size_t count);
-
-#ifndef PRODUCT
-  static bool contains_loader_data(ClassLoaderData* loader_data);
-#endif
-};
-
-class LockedClassesDo : public KlassClosure {
-  typedef void (*classes_do_func_t)(Klass*);
-  classes_do_func_t _function;
-public:
-  LockedClassesDo();  // For callers who provide their own do_klass
-  LockedClassesDo(classes_do_func_t function);
-  ~LockedClassesDo();
-
-  void do_klass(Klass* k) {
-    (*_function)(k);
-  }
-};
-
-
 // ClassLoaderData class
 
 class ClassLoaderData : public CHeapObj<mtClass> {
@@ -448,31 +317,4 @@
   JFR_ONLY(DEFINE_TRACE_ID_METHODS;)
 };
 
-// An iterator that distributes Klasses to parallel worker threads.
-class ClassLoaderDataGraphKlassIteratorAtomic : public StackObj {
- Klass* volatile _next_klass;
- public:
-  ClassLoaderDataGraphKlassIteratorAtomic();
-  Klass* next_klass();
- private:
-  static Klass* next_klass_in_cldg(Klass* klass);
-};
-
-class ClassLoaderDataGraphMetaspaceIterator : public StackObj {
-  ClassLoaderData* _data;
- public:
-  ClassLoaderDataGraphMetaspaceIterator();
-  ~ClassLoaderDataGraphMetaspaceIterator();
-  bool repeat() { return _data != NULL; }
-  ClassLoaderMetaspace* get_next() {
-    assert(_data != NULL, "Should not be NULL in call to the iterator");
-    ClassLoaderMetaspace* result = _data->metaspace_or_null();
-    _data = _data->next();
-    // This result might be NULL for class loaders without metaspace
-    // yet.  It would be nice to return only non-null results but
-    // there is no guarantee that there will be a non-null result
-    // down the list so the caller is going to have to check.
-    return result;
-  }
-};
 #endif // SHARE_VM_CLASSFILE_CLASSLOADERDATA_HPP
--- a/src/hotspot/share/classfile/classLoaderData.inline.hpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/hotspot/share/classfile/classLoaderData.inline.hpp	Mon Oct 01 09:56:45 2018 +0100
@@ -55,54 +55,4 @@
   return loader_data;
 }
 
-
-inline ClassLoaderData *ClassLoaderDataGraph::find_or_create(Handle loader) {
-  guarantee(loader() != NULL && oopDesc::is_oop(loader()), "Loader must be oop");
-  // Gets the class loader data out of the java/lang/ClassLoader object, if non-null
-  // it's already in the loader_data, so no need to add
-  ClassLoaderData* loader_data= java_lang_ClassLoader::loader_data_acquire(loader());
-  if (loader_data) {
-     return loader_data;
-  }
-  return ClassLoaderDataGraph::add(loader, false);
-}
-
-size_t ClassLoaderDataGraph::num_instance_classes() {
-  return _num_instance_classes;
-}
-
-size_t ClassLoaderDataGraph::num_array_classes() {
-  return _num_array_classes;
-}
-
-void ClassLoaderDataGraph::inc_instance_classes(size_t count) {
-  Atomic::add(count, &_num_instance_classes);
-}
-
-void ClassLoaderDataGraph::dec_instance_classes(size_t count) {
-  assert(count <= _num_instance_classes, "Sanity");
-  Atomic::sub(count, &_num_instance_classes);
-}
-
-void ClassLoaderDataGraph::inc_array_classes(size_t count) {
-  Atomic::add(count, &_num_array_classes);
-}
-
-void ClassLoaderDataGraph::dec_array_classes(size_t count) {
-  assert(count <= _num_array_classes, "Sanity");
-  Atomic::sub(count, &_num_array_classes);
-}
-
-bool ClassLoaderDataGraph::should_clean_metaspaces_and_reset() {
-  // Only clean metaspaces after full GC.
-  bool do_cleaning = _safepoint_cleanup_needed;
-#if INCLUDE_JVMTI
-  do_cleaning = do_cleaning && (_should_clean_deallocate_lists || InstanceKlass::has_previous_versions());
-#else
-  do_cleaning = do_cleaning && _should_clean_deallocate_lists;
-#endif
-  _safepoint_cleanup_needed = false;  // reset
-  return do_cleaning;
-}
-
 #endif // SHARE_VM_CLASSFILE_CLASSLOADERDATA_INLINE_HPP
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/hotspot/share/classfile/classLoaderDataGraph.cpp	Mon Oct 01 09:56:45 2018 +0100
@@ -0,0 +1,697 @@
+/*
+ * 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 "classfile/classLoaderDataGraph.inline.hpp"
+#include "classfile/dictionary.hpp"
+#include "classfile/javaClasses.hpp"
+#include "classfile/metadataOnStackMark.hpp"
+#include "classfile/moduleEntry.hpp"
+#include "classfile/packageEntry.hpp"
+#include "logging/log.hpp"
+#include "logging/logStream.hpp"
+#include "memory/allocation.inline.hpp"
+#include "memory/metaspace.hpp"
+#include "memory/resourceArea.hpp"
+#include "runtime/atomic.hpp"
+#include "runtime/handles.inline.hpp"
+#include "runtime/mutex.hpp"
+#include "runtime/safepoint.hpp"
+#include "runtime/safepointVerifiers.hpp"
+#include "utilities/growableArray.hpp"
+#include "utilities/macros.hpp"
+#include "utilities/ostream.hpp"
+
+volatile size_t ClassLoaderDataGraph::_num_array_classes = 0;
+volatile size_t ClassLoaderDataGraph::_num_instance_classes = 0;
+
+void ClassLoaderDataGraph::clear_claimed_marks() {
+  for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
+    cld->clear_claimed();
+  }
+}
+
+// Class iterator used by the compiler.  It gets some number of classes at
+// a safepoint to decay invocation counters on the methods.
+class ClassLoaderDataGraphKlassIteratorStatic {
+  ClassLoaderData* _current_loader_data;
+  Klass*           _current_class_entry;
+ public:
+
+  ClassLoaderDataGraphKlassIteratorStatic() : _current_loader_data(NULL), _current_class_entry(NULL) {}
+
+  InstanceKlass* try_get_next_class() {
+    assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
+    size_t max_classes = ClassLoaderDataGraph::num_instance_classes();
+    assert(max_classes > 0, "should not be called with no instance classes");
+    for (size_t i = 0; i < max_classes; ) {
+
+      if (_current_class_entry != NULL) {
+        Klass* k = _current_class_entry;
+        _current_class_entry = _current_class_entry->next_link();
+
+        if (k->is_instance_klass()) {
+          InstanceKlass* ik = InstanceKlass::cast(k);
+          i++;  // count all instance classes found
+          // Not yet loaded classes are counted in max_classes
+          // but only return loaded classes.
+          if (ik->is_loaded()) {
+            return ik;
+          }
+        }
+      } else {
+        // Go to next CLD
+        if (_current_loader_data != NULL) {
+          _current_loader_data = _current_loader_data->next();
+        }
+        // Start at the beginning
+        if (_current_loader_data == NULL) {
+          _current_loader_data = ClassLoaderDataGraph::_head;
+        }
+
+        _current_class_entry = _current_loader_data->klasses();
+      }
+    }
+    // Should never be reached unless all instance classes have failed or are not fully loaded.
+    // Caller handles NULL.
+    return NULL;
+  }
+
+  // If the current class for the static iterator is a class being unloaded or
+  // deallocated, adjust the current class.
+  void adjust_saved_class(ClassLoaderData* cld) {
+    if (_current_loader_data == cld) {
+      _current_loader_data = cld->next();
+      if (_current_loader_data != NULL) {
+        _current_class_entry = _current_loader_data->klasses();
+      }  // else try_get_next_class will start at the head
+    }
+  }
+
+  void adjust_saved_class(Klass* klass) {
+    if (_current_class_entry == klass) {
+      _current_class_entry = klass->next_link();
+    }
+  }
+};
+
+static ClassLoaderDataGraphKlassIteratorStatic static_klass_iterator;
+
+InstanceKlass* ClassLoaderDataGraph::try_get_next_class() {
+  assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
+  return static_klass_iterator.try_get_next_class();
+}
+
+void ClassLoaderDataGraph::adjust_saved_class(ClassLoaderData* cld) {
+  return static_klass_iterator.adjust_saved_class(cld);
+}
+
+void ClassLoaderDataGraph::adjust_saved_class(Klass* klass) {
+  return static_klass_iterator.adjust_saved_class(klass);
+}
+
+void ClassLoaderDataGraph::clean_deallocate_lists(bool walk_previous_versions) {
+  assert(SafepointSynchronize::is_at_safepoint(), "must only be called at safepoint");
+  uint loaders_processed = 0;
+  for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
+    // is_alive check will be necessary for concurrent class unloading.
+    if (cld->is_alive()) {
+      // clean metaspace
+      if (walk_previous_versions) {
+        cld->classes_do(InstanceKlass::purge_previous_versions);
+      }
+      cld->free_deallocate_list();
+      loaders_processed++;
+    }
+  }
+  log_debug(class, loader, data)("clean_deallocate_lists: loaders processed %u %s",
+                                 loaders_processed, walk_previous_versions ? "walk_previous_versions" : "");
+}
+
+void ClassLoaderDataGraph::walk_metadata_and_clean_metaspaces() {
+  assert(SafepointSynchronize::is_at_safepoint(), "must only be called at safepoint");
+
+  _should_clean_deallocate_lists = false; // assume everything gets cleaned
+
+  // Mark metadata seen on the stack so we can delete unreferenced entries.
+  // Walk all metadata, including the expensive code cache walk, only for class redefinition.
+  // The MetadataOnStackMark walk during redefinition saves previous versions if it finds old methods
+  // on the stack or in the code cache, so we only have to repeat the full walk if
+  // they were found at that time.
+  // TODO: have redefinition clean old methods out of the code cache.  They still exist in some places.
+  bool walk_all_metadata = InstanceKlass::has_previous_versions_and_reset();
+
+  MetadataOnStackMark md_on_stack(walk_all_metadata);
+  clean_deallocate_lists(walk_all_metadata);
+}
+
+// GC root of class loader data created.
+ClassLoaderData* ClassLoaderDataGraph::_head = NULL;
+ClassLoaderData* ClassLoaderDataGraph::_unloading = NULL;
+ClassLoaderData* ClassLoaderDataGraph::_saved_unloading = NULL;
+ClassLoaderData* ClassLoaderDataGraph::_saved_head = NULL;
+
+bool ClassLoaderDataGraph::_should_purge = false;
+bool ClassLoaderDataGraph::_should_clean_deallocate_lists = false;
+bool ClassLoaderDataGraph::_safepoint_cleanup_needed = false;
+bool ClassLoaderDataGraph::_metaspace_oom = false;
+
+// Add a new class loader data node to the list.  Assign the newly created
+// ClassLoaderData into the java/lang/ClassLoader object as a hidden field
+ClassLoaderData* ClassLoaderDataGraph::add_to_graph(Handle loader, bool is_unsafe_anonymous) {
+
+  assert_lock_strong(ClassLoaderDataGraph_lock);
+
+  ClassLoaderData* cld;
+
+  // First check if another thread beat us to creating the CLD and installing
+  // it into the loader while we were waiting for the lock.
+  if (!is_unsafe_anonymous && loader.not_null()) {
+    cld = java_lang_ClassLoader::loader_data_acquire(loader());
+    if (cld != NULL) {
+      return cld;
+    }
+  }
+
+  // We mustn't GC until we've installed the ClassLoaderData in the Graph since the CLD
+  // contains oops in _handles that must be walked.  GC doesn't walk CLD from the
+  // loader oop in all collections, particularly young collections.
+  NoSafepointVerifier no_safepoints;
+
+  cld = new ClassLoaderData(loader, is_unsafe_anonymous);
+
+  // First install the new CLD to the Graph.
+  cld->set_next(_head);
+  _head = cld;
+
+  // Next associate with the class_loader.
+  if (!is_unsafe_anonymous) {
+    // Use OrderAccess, since readers need to get the loader_data only after
+    // it's added to the Graph
+    java_lang_ClassLoader::release_set_loader_data(loader(), cld);
+  }
+
+  // Lastly log, if requested
+  LogTarget(Trace, class, loader, data) lt;
+  if (lt.is_enabled()) {
+    ResourceMark rm;
+    LogStream ls(lt);
+    ls.print("create ");
+    cld->print_value_on(&ls);
+    ls.cr();
+  }
+  return cld;
+}
+
+ClassLoaderData* ClassLoaderDataGraph::add(Handle loader, bool is_unsafe_anonymous) {
+  MutexLocker ml(ClassLoaderDataGraph_lock);
+  ClassLoaderData* loader_data = add_to_graph(loader, is_unsafe_anonymous);
+  return loader_data;
+}
+
+void ClassLoaderDataGraph::cld_do(CLDClosure* cl) {
+  assert_locked_or_safepoint(ClassLoaderDataGraph_lock);
+  for (ClassLoaderData* cld = _head;  cld != NULL; cld = cld->_next) {
+    cl->do_cld(cld);
+  }
+}
+
+void ClassLoaderDataGraph::cld_unloading_do(CLDClosure* cl) {
+  assert_locked_or_safepoint(ClassLoaderDataGraph_lock);
+  // Only walk the head until any clds not purged from prior unloading
+  // (CMS doesn't purge right away).
+  for (ClassLoaderData* cld = _unloading; cld != _saved_unloading; cld = cld->next()) {
+    assert(cld->is_unloading(), "invariant");
+    cl->do_cld(cld);
+  }
+}
+
+void ClassLoaderDataGraph::roots_cld_do(CLDClosure* strong, CLDClosure* weak) {
+  assert_locked_or_safepoint(ClassLoaderDataGraph_lock);
+  for (ClassLoaderData* cld = _head;  cld != NULL; cld = cld->_next) {
+    CLDClosure* closure = cld->keep_alive() ? strong : weak;
+    if (closure != NULL) {
+      closure->do_cld(cld);
+    }
+  }
+}
+
+void ClassLoaderDataGraph::always_strong_cld_do(CLDClosure* cl) {
+  assert_locked_or_safepoint(ClassLoaderDataGraph_lock);
+  if (ClassUnloading) {
+    roots_cld_do(cl, NULL);
+  } else {
+    cld_do(cl);
+  }
+}
+
+// Closure for locking and iterating through classes.
+LockedClassesDo::LockedClassesDo(classes_do_func_t f) : _function(f) {
+  ClassLoaderDataGraph_lock->lock();
+}
+
+LockedClassesDo::LockedClassesDo() : _function(NULL) {
+  // callers provide their own do_klass
+  ClassLoaderDataGraph_lock->lock();
+}
+
+LockedClassesDo::~LockedClassesDo() { ClassLoaderDataGraph_lock->unlock(); }
+
+
+// Iterating over the CLDG needs to be locked because
+// unloading can remove entries concurrently soon.
+class ClassLoaderDataGraphIterator : public StackObj {
+  ClassLoaderData* _next;
+  HandleMark       _hm;  // clean up handles when this is done.
+  Handle           _holder;
+  Thread*          _thread;
+
+  void hold_next() {
+    if (_next != NULL) {
+      _holder = Handle(_thread, _next->holder_phantom());
+    }
+  }
+public:
+  ClassLoaderDataGraphIterator() : _next(ClassLoaderDataGraph::_head) {
+    _thread = Thread::current();
+    assert_locked_or_safepoint(ClassLoaderDataGraph_lock);
+    hold_next();
+  }
+
+  bool repeat() const {
+    return _next != NULL;
+  }
+
+  ClassLoaderData* get_next() {
+    ClassLoaderData* next = _next;
+    if (_next != NULL) {
+      _next = _next->next();
+      hold_next();
+    }
+    return next;
+  }
+};
+
+// These functions assume that the caller has locked the ClassLoaderDataGraph_lock
+// if they are not calling the function from a safepoint.
+void ClassLoaderDataGraph::classes_do(KlassClosure* klass_closure) {
+  ClassLoaderDataGraphIterator iter;
+  while (iter.repeat()) {
+    ClassLoaderData* cld = iter.get_next();
+    cld->classes_do(klass_closure);
+  }
+}
+
+void ClassLoaderDataGraph::classes_do(void f(Klass* const)) {
+  ClassLoaderDataGraphIterator iter;
+  while (iter.repeat()) {
+    ClassLoaderData* cld = iter.get_next();
+    cld->classes_do(f);
+  }
+}
+
+void ClassLoaderDataGraph::methods_do(void f(Method*)) {
+  ClassLoaderDataGraphIterator iter;
+  while (iter.repeat()) {
+    ClassLoaderData* cld = iter.get_next();
+    cld->methods_do(f);
+  }
+}
+
+void ClassLoaderDataGraph::modules_do(void f(ModuleEntry*)) {
+  assert_locked_or_safepoint(Module_lock);
+  ClassLoaderDataGraphIterator iter;
+  while (iter.repeat()) {
+    ClassLoaderData* cld = iter.get_next();
+    cld->modules_do(f);
+  }
+}
+
+void ClassLoaderDataGraph::modules_unloading_do(void f(ModuleEntry*)) {
+  assert_locked_or_safepoint(ClassLoaderDataGraph_lock);
+  // Only walk the head until any clds not purged from prior unloading
+  // (CMS doesn't purge right away).
+  for (ClassLoaderData* cld = _unloading; cld != _saved_unloading; cld = cld->next()) {
+    assert(cld->is_unloading(), "invariant");
+    cld->modules_do(f);
+  }
+}
+
+void ClassLoaderDataGraph::packages_do(void f(PackageEntry*)) {
+  assert_locked_or_safepoint(Module_lock);
+  ClassLoaderDataGraphIterator iter;
+  while (iter.repeat()) {
+    ClassLoaderData* cld = iter.get_next();
+    cld->packages_do(f);
+  }
+}
+
+void ClassLoaderDataGraph::packages_unloading_do(void f(PackageEntry*)) {
+  assert_locked_or_safepoint(ClassLoaderDataGraph_lock);
+  // Only walk the head until any clds not purged from prior unloading
+  // (CMS doesn't purge right away).
+  for (ClassLoaderData* cld = _unloading; cld != _saved_unloading; cld = cld->next()) {
+    assert(cld->is_unloading(), "invariant");
+    cld->packages_do(f);
+  }
+}
+
+void ClassLoaderDataGraph::loaded_classes_do(KlassClosure* klass_closure) {
+  ClassLoaderDataGraphIterator iter;
+  while (iter.repeat()) {
+    ClassLoaderData* cld = iter.get_next();
+    cld->loaded_classes_do(klass_closure);
+  }
+}
+
+// This case can block but cannot do unloading (called from CDS)
+void ClassLoaderDataGraph::unlocked_loaded_classes_do(KlassClosure* klass_closure) {
+  for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) {
+    cld->loaded_classes_do(klass_closure);
+  }
+}
+
+
+void ClassLoaderDataGraph::classes_unloading_do(void f(Klass* const)) {
+  assert_locked_or_safepoint(ClassLoaderDataGraph_lock);
+  // Only walk the head until any clds not purged from prior unloading
+  // (CMS doesn't purge right away).
+  for (ClassLoaderData* cld = _unloading; cld != _saved_unloading; cld = cld->next()) {
+    assert(cld->is_unloading(), "invariant");
+    cld->classes_do(f);
+  }
+}
+
+#define FOR_ALL_DICTIONARY(X)   ClassLoaderDataGraphIterator iter; \
+                                ClassLoaderData* X; \
+                                while ((X = iter.get_next()) != NULL) \
+                                  if (X->dictionary() != NULL)
+
+// Walk classes in the loaded class dictionaries in various forms.
+// Only walks the classes defined in this class loader.
+void ClassLoaderDataGraph::dictionary_classes_do(void f(InstanceKlass*)) {
+  FOR_ALL_DICTIONARY(cld) {
+    cld->dictionary()->classes_do(f);
+  }
+}
+
+// Only walks the classes defined in this class loader.
+void ClassLoaderDataGraph::dictionary_classes_do(void f(InstanceKlass*, TRAPS), TRAPS) {
+  FOR_ALL_DICTIONARY(cld) {
+    cld->dictionary()->classes_do(f, CHECK);
+  }
+}
+
+void ClassLoaderDataGraph::verify_dictionary() {
+  FOR_ALL_DICTIONARY(cld) {
+    cld->dictionary()->verify();
+  }
+}
+
+void ClassLoaderDataGraph::print_dictionary(outputStream* st) {
+  FOR_ALL_DICTIONARY(cld) {
+    st->print("Dictionary for ");
+    cld->print_value_on(st);
+    st->cr();
+    cld->dictionary()->print_on(st);
+    st->cr();
+  }
+}
+
+void ClassLoaderDataGraph::print_dictionary_statistics(outputStream* st) {
+  FOR_ALL_DICTIONARY(cld) {
+    ResourceMark rm;
+    stringStream tempst;
+    tempst.print("System Dictionary for %s class loader", cld->loader_name_and_id());
+    cld->dictionary()->print_table_statistics(st, tempst.as_string());
+  }
+}
+
+GrowableArray<ClassLoaderData*>* ClassLoaderDataGraph::new_clds() {
+  assert_locked_or_safepoint(ClassLoaderDataGraph_lock);
+  assert(_head == NULL || _saved_head != NULL, "remember_new_clds(true) not called?");
+
+  GrowableArray<ClassLoaderData*>* array = new GrowableArray<ClassLoaderData*>();
+
+  // The CLDs in [_head, _saved_head] were all added during last call to remember_new_clds(true);
+  ClassLoaderData* curr = _head;
+  while (curr != _saved_head) {
+    if (!curr->claimed()) {
+      array->push(curr);
+      LogTarget(Debug, class, loader, data) lt;
+      if (lt.is_enabled()) {
+        LogStream ls(lt);
+        ls.print("found new CLD: ");
+        curr->print_value_on(&ls);
+        ls.cr();
+      }
+    }
+
+    curr = curr->_next;
+  }
+
+  return array;
+}
+
+#ifndef PRODUCT
+bool ClassLoaderDataGraph::contains_loader_data(ClassLoaderData* loader_data) {
+  assert_locked_or_safepoint(ClassLoaderDataGraph_lock);
+  for (ClassLoaderData* data = _head; data != NULL; data = data->next()) {
+    if (loader_data == data) {
+      return true;
+    }
+  }
+
+  return false;
+}
+#endif // PRODUCT
+
+// Move class loader data from main list to the unloaded list for unloading
+// and deallocation later.
+bool ClassLoaderDataGraph::do_unloading(bool do_cleaning) {
+  assert_locked_or_safepoint(ClassLoaderDataGraph_lock);
+
+  // Indicate whether safepoint cleanup is needed.
+  _safepoint_cleanup_needed |= do_cleaning;
+
+  ClassLoaderData* data = _head;
+  ClassLoaderData* prev = NULL;
+  bool seen_dead_loader = false;
+  uint loaders_processed = 0;
+  uint loaders_removed = 0;
+
+  // Save previous _unloading pointer for CMS which may add to unloading list before
+  // purging and we don't want to rewalk the previously unloaded class loader data.
+  _saved_unloading = _unloading;
+
+  data = _head;
+  while (data != NULL) {
+    if (data->is_alive()) {
+      prev = data;
+      data = data->next();
+      loaders_processed++;
+      continue;
+    }
+    seen_dead_loader = true;
+    loaders_removed++;
+    ClassLoaderData* dead = data;
+    dead->unload();
+    data = data->next();
+    // Remove from loader list.
+    // This class loader data will no longer be found
+    // in the ClassLoaderDataGraph.
+    if (prev != NULL) {
+      prev->set_next(data);
+    } else {
+      assert(dead == _head, "sanity check");
+      _head = data;
+    }
+    dead->set_next(_unloading);
+    _unloading = dead;
+  }
+
+  log_debug(class, loader, data)("do_unloading: loaders processed %u, loaders removed %u", loaders_processed, loaders_removed);
+
+  return seen_dead_loader;
+}
+
+// There's at least one dead class loader.  Purge refererences of healthy module
+// reads lists and package export lists to modules belonging to dead loaders.
+void ClassLoaderDataGraph::clean_module_and_package_info() {
+  assert_locked_or_safepoint(ClassLoaderDataGraph_lock);
+
+  ClassLoaderData* data = _head;
+  while (data != NULL) {
+    // Remove entries in the dictionary of live class loader that have
+    // initiated loading classes in a dead class loader.
+    if (data->dictionary() != NULL) {
+      data->dictionary()->do_unloading();
+    }
+    // Walk a ModuleEntry's reads, and a PackageEntry's exports
+    // lists to determine if there are modules on those lists that are now
+    // dead and should be removed.  A module's life cycle is equivalent
+    // to its defining class loader's life cycle.  Since a module is
+    // considered dead if its class loader is dead, these walks must
+    // occur after each class loader's aliveness is determined.
+    if (data->packages() != NULL) {
+      data->packages()->purge_all_package_exports();
+    }
+    if (data->modules_defined()) {
+      data->modules()->purge_all_module_reads();
+    }
+    data = data->next();
+  }
+}
+
+void ClassLoaderDataGraph::purge() {
+  assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint!");
+  ClassLoaderData* list = _unloading;
+  _unloading = NULL;
+  ClassLoaderData* next = list;
+  bool classes_unloaded = false;
+  while (next != NULL) {
+    ClassLoaderData* purge_me = next;
+    next = purge_me->next();
+    delete purge_me;
+    classes_unloaded = true;
+  }
+  if (classes_unloaded) {
+    Metaspace::purge();
+    set_metaspace_oom(false);
+  }
+}
+
+int ClassLoaderDataGraph::resize_if_needed() {
+  assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint!");
+  int resized = 0;
+  if (Dictionary::does_any_dictionary_needs_resizing()) {
+    FOR_ALL_DICTIONARY(cld) {
+      if (cld->dictionary()->resize_if_needed()) {
+        resized++;
+      }
+    }
+  }
+  return resized;
+}
+
+ClassLoaderDataGraphKlassIteratorAtomic::ClassLoaderDataGraphKlassIteratorAtomic()
+    : _next_klass(NULL) {
+  assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint!");
+  ClassLoaderData* cld = ClassLoaderDataGraph::_head;
+  Klass* klass = NULL;
+
+  // Find the first klass in the CLDG.
+  while (cld != NULL) {
+    assert_locked_or_safepoint(cld->metaspace_lock());
+    klass = cld->_klasses;
+    if (klass != NULL) {
+      _next_klass = klass;
+      return;
+    }
+    cld = cld->next();
+  }
+}
+
+Klass* ClassLoaderDataGraphKlassIteratorAtomic::next_klass_in_cldg(Klass* klass) {
+  Klass* next = klass->next_link();
+  if (next != NULL) {
+    return next;
+  }
+
+  // No more klasses in the current CLD. Time to find a new CLD.
+  ClassLoaderData* cld = klass->class_loader_data();
+  assert_locked_or_safepoint(cld->metaspace_lock());
+  while (next == NULL) {
+    cld = cld->next();
+    if (cld == NULL) {
+      break;
+    }
+    next = cld->_klasses;
+  }
+
+  return next;
+}
+
+Klass* ClassLoaderDataGraphKlassIteratorAtomic::next_klass() {
+  Klass* head = _next_klass;
+
+  while (head != NULL) {
+    Klass* next = next_klass_in_cldg(head);
+
+    Klass* old_head = Atomic::cmpxchg(next, &_next_klass, head);
+
+    if (old_head == head) {
+      return head; // Won the CAS.
+    }
+
+    head = old_head;
+  }
+
+  // Nothing more for the iterator to hand out.
+  assert(head == NULL, "head is " PTR_FORMAT ", expected not null:", p2i(head));
+  return NULL;
+}
+
+ClassLoaderDataGraphMetaspaceIterator::ClassLoaderDataGraphMetaspaceIterator() {
+  assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint!");
+  _data = ClassLoaderDataGraph::_head;
+}
+
+ClassLoaderDataGraphMetaspaceIterator::~ClassLoaderDataGraphMetaspaceIterator() {}
+
+ClassLoaderMetaspace* ClassLoaderDataGraphMetaspaceIterator::get_next() {
+  assert(_data != NULL, "Should not be NULL in call to the iterator");
+  ClassLoaderMetaspace* result = _data->metaspace_or_null();
+  _data = _data->next();
+  // This result might be NULL for class loaders without metaspace
+  // yet.  It would be nice to return only non-null results but
+  // there is no guarantee that there will be a non-null result
+  // down the list so the caller is going to have to check.
+  return result;
+}
+
+#ifndef PRODUCT
+// callable from debugger
+extern "C" int print_loader_data_graph() {
+  ResourceMark rm;
+  ClassLoaderDataGraph::print_on(tty);
+  return 0;
+}
+
+void ClassLoaderDataGraph::verify() {
+  ClassLoaderDataGraphIterator iter;
+  while (iter.repeat()) {
+    ClassLoaderData* cld = iter.get_next();
+    cld->verify();
+  }
+}
+
+void ClassLoaderDataGraph::print_on(outputStream * const out) {
+  ClassLoaderDataGraphIterator iter;
+  while (iter.repeat()) {
+    ClassLoaderData* cld = iter.get_next();
+    cld->print_on(out);
+  }
+}
+#endif // PRODUCT
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/hotspot/share/classfile/classLoaderDataGraph.hpp	Mon Oct 01 09:56:45 2018 +0100
@@ -0,0 +1,182 @@
+/*
+ * 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.
+ *
+ */
+
+#ifndef SHARE_VM_CLASSFILE_CLASSLOADERDATAGRAPH_HPP
+#define SHARE_VM_CLASSFILE_CLASSLOADERDATAGRAPH_HPP
+
+#include "classfile/classLoaderData.hpp"
+#include "memory/allocation.hpp"
+#include "utilities/growableArray.hpp"
+#include "utilities/macros.hpp"
+
+// GC root for walking class loader data created
+
+class ClassLoaderDataGraph : public AllStatic {
+  friend class ClassLoaderData;
+  friend class ClassLoaderDataGraphMetaspaceIterator;
+  friend class ClassLoaderDataGraphKlassIteratorAtomic;
+  friend class ClassLoaderDataGraphKlassIteratorStatic;
+  friend class ClassLoaderDataGraphIterator;
+  friend class VMStructs;
+ private:
+  // All CLDs (except the null CLD) can be reached by walking _head->_next->...
+  static ClassLoaderData* _head;
+  static ClassLoaderData* _unloading;
+  // CMS support.
+  static ClassLoaderData* _saved_head;
+  static ClassLoaderData* _saved_unloading;
+  static bool _should_purge;
+
+  // Set if there's anything to purge in the deallocate lists or previous versions
+  // during a safepoint after class unloading in a full GC.
+  static bool _should_clean_deallocate_lists;
+  static bool _safepoint_cleanup_needed;
+
+  // OOM has been seen in metaspace allocation. Used to prevent some
+  // allocations until class unloading
+  static bool _metaspace_oom;
+
+  static volatile size_t  _num_instance_classes;
+  static volatile size_t  _num_array_classes;
+
+  static ClassLoaderData* add_to_graph(Handle class_loader, bool is_unsafe_anonymous);
+  static ClassLoaderData* add(Handle class_loader, bool is_unsafe_anonymous);
+
+ public:
+  static ClassLoaderData* find_or_create(Handle class_loader);
+  static void clean_module_and_package_info();
+  static void purge();
+  static void clear_claimed_marks();
+  // Iteration through CLDG inside a safepoint; GC support
+  static void cld_do(CLDClosure* cl);
+  static void cld_unloading_do(CLDClosure* cl);
+  static void roots_cld_do(CLDClosure* strong, CLDClosure* weak);
+  static void always_strong_cld_do(CLDClosure* cl);
+  // klass do
+  // Walking classes through the ClassLoaderDataGraph include array classes.  It also includes
+  // classes that are allocated but not loaded, classes that have errors, and scratch classes
+  // for redefinition.  These classes are removed during the next class unloading.
+  // Walking the ClassLoaderDataGraph also includes unsafe anonymous classes.
+  static void classes_do(KlassClosure* klass_closure);
+  static void classes_do(void f(Klass* const));
+  static void methods_do(void f(Method*));
+  static void modules_do(void f(ModuleEntry*));
+  static void modules_unloading_do(void f(ModuleEntry*));
+  static void packages_do(void f(PackageEntry*));
+  static void packages_unloading_do(void f(PackageEntry*));
+  static void loaded_classes_do(KlassClosure* klass_closure);
+  static void unlocked_loaded_classes_do(KlassClosure* klass_closure);
+  static void classes_unloading_do(void f(Klass* const));
+  static bool do_unloading(bool do_cleaning);
+
+  // Expose state to avoid logging overhead in safepoint cleanup tasks.
+  static inline bool should_clean_metaspaces_and_reset();
+  static void set_should_clean_deallocate_lists() { _should_clean_deallocate_lists = true; }
+  static void clean_deallocate_lists(bool purge_previous_versions);
+  static void walk_metadata_and_clean_metaspaces();
+
+  // dictionary do
+  // Iterate over all klasses in dictionary, but
+  // just the classes from defining class loaders.
+  static void dictionary_classes_do(void f(InstanceKlass*));
+  // Added for initialize_itable_for_klass to handle exceptions.
+  static void dictionary_classes_do(void f(InstanceKlass*, TRAPS), TRAPS);
+
+  // VM_CounterDecay iteration support
+  static InstanceKlass* try_get_next_class();
+  static void adjust_saved_class(ClassLoaderData* cld);
+  static void adjust_saved_class(Klass* klass);
+
+  static void verify_dictionary();
+  static void print_dictionary(outputStream* st);
+  static void print_dictionary_statistics(outputStream* st);
+
+  // CMS support.
+  static void remember_new_clds(bool remember) { _saved_head = (remember ? _head : NULL); }
+  static GrowableArray<ClassLoaderData*>* new_clds();
+
+  static void set_should_purge(bool b) { _should_purge = b; }
+  static void purge_if_needed() {
+    // Only purge the CLDG for CMS if concurrent sweep is complete.
+    if (_should_purge) {
+      purge();
+      // reset for next time.
+      set_should_purge(false);
+    }
+  }
+
+  static int resize_if_needed();
+
+  static bool has_metaspace_oom()           { return _metaspace_oom; }
+  static void set_metaspace_oom(bool value) { _metaspace_oom = value; }
+
+  static void print_on(outputStream * const out) PRODUCT_RETURN;
+  static void print() { print_on(tty); }
+  static void verify();
+
+  // instance and array class counters
+  static inline size_t num_instance_classes();
+  static inline size_t num_array_classes();
+  static inline void inc_instance_classes(size_t count);
+  static inline void dec_instance_classes(size_t count);
+  static inline void inc_array_classes(size_t count);
+  static inline void dec_array_classes(size_t count);
+
+#ifndef PRODUCT
+  static bool contains_loader_data(ClassLoaderData* loader_data);
+#endif
+};
+
+class LockedClassesDo : public KlassClosure {
+  typedef void (*classes_do_func_t)(Klass*);
+  classes_do_func_t _function;
+public:
+  LockedClassesDo();  // For callers who provide their own do_klass
+  LockedClassesDo(classes_do_func_t function);
+  ~LockedClassesDo();
+
+  void do_klass(Klass* k) {
+    (*_function)(k);
+  }
+};
+
+// An iterator that distributes Klasses to parallel worker threads.
+class ClassLoaderDataGraphKlassIteratorAtomic : public StackObj {
+ Klass* volatile _next_klass;
+ public:
+  ClassLoaderDataGraphKlassIteratorAtomic();
+  Klass* next_klass();
+ private:
+  static Klass* next_klass_in_cldg(Klass* klass);
+};
+
+class ClassLoaderDataGraphMetaspaceIterator : public StackObj {
+  ClassLoaderData* _data;
+ public:
+  ClassLoaderDataGraphMetaspaceIterator();
+  ~ClassLoaderDataGraphMetaspaceIterator();
+  bool repeat() { return _data != NULL; }
+  ClassLoaderMetaspace* get_next();
+};
+#endif // SHARE_VM_CLASSFILE_CLASSLOADERDATAGRAPH_HPP
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/hotspot/share/classfile/classLoaderDataGraph.inline.hpp	Mon Oct 01 09:56:45 2018 +0100
@@ -0,0 +1,82 @@
+/*
+ * 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.
+ *
+ */
+
+#ifndef SHARE_VM_CLASSFILE_CLASSLOADERDATAGRAPH_INLINE_HPP
+#define SHARE_VM_CLASSFILE_CLASSLOADERDATAGRAPH_INLINE_HPP
+
+#include "classfile/classLoaderDataGraph.hpp"
+#include "classfile/javaClasses.hpp"
+#include "oops/oop.inline.hpp"
+#include "runtime/atomic.hpp"
+
+inline ClassLoaderData *ClassLoaderDataGraph::find_or_create(Handle loader) {
+  guarantee(loader() != NULL && oopDesc::is_oop(loader()), "Loader must be oop");
+  // Gets the class loader data out of the java/lang/ClassLoader object, if non-null
+  // it's already in the loader_data, so no need to add
+  ClassLoaderData* loader_data = java_lang_ClassLoader::loader_data_acquire(loader());
+  if (loader_data) {
+     return loader_data;
+  }
+  return ClassLoaderDataGraph::add(loader, false);
+}
+
+size_t ClassLoaderDataGraph::num_instance_classes() {
+  return _num_instance_classes;
+}
+
+size_t ClassLoaderDataGraph::num_array_classes() {
+  return _num_array_classes;
+}
+
+void ClassLoaderDataGraph::inc_instance_classes(size_t count) {
+  Atomic::add(count, &_num_instance_classes);
+}
+
+void ClassLoaderDataGraph::dec_instance_classes(size_t count) {
+  assert(count <= _num_instance_classes, "Sanity");
+  Atomic::sub(count, &_num_instance_classes);
+}
+
+void ClassLoaderDataGraph::inc_array_classes(size_t count) {
+  Atomic::add(count, &_num_array_classes);
+}
+
+void ClassLoaderDataGraph::dec_array_classes(size_t count) {
+  assert(count <= _num_array_classes, "Sanity");
+  Atomic::sub(count, &_num_array_classes);
+}
+
+bool ClassLoaderDataGraph::should_clean_metaspaces_and_reset() {
+  // Only clean metaspaces after full GC.
+  bool do_cleaning = _safepoint_cleanup_needed;
+#if INCLUDE_JVMTI
+  do_cleaning = do_cleaning && (_should_clean_deallocate_lists || InstanceKlass::has_previous_versions());
+#else
+  do_cleaning = do_cleaning && _should_clean_deallocate_lists;
+#endif
+  _safepoint_cleanup_needed = false;  // reset
+  return do_cleaning;
+}
+
+#endif // SHARE_VM_CLASSFILE_CLASSLOADERDATAGRAPH_INLINE_HPP
--- a/src/hotspot/share/classfile/classLoaderHierarchyDCmd.cpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/hotspot/share/classfile/classLoaderHierarchyDCmd.cpp	Mon Oct 01 09:56:45 2018 +0100
@@ -26,6 +26,7 @@
 #include "precompiled.hpp"
 
 #include "classfile/classLoaderData.inline.hpp"
+#include "classfile/classLoaderDataGraph.hpp"
 #include "classfile/classLoaderHierarchyDCmd.hpp"
 #include "memory/allocation.hpp"
 #include "memory/resourceArea.hpp"
--- a/src/hotspot/share/classfile/classLoaderStats.cpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/hotspot/share/classfile/classLoaderStats.cpp	Mon Oct 01 09:56:45 2018 +0100
@@ -24,6 +24,7 @@
 
 #include "precompiled.hpp"
 #include "classfile/classLoaderData.inline.hpp"
+#include "classfile/classLoaderDataGraph.hpp"
 #include "classfile/classLoaderStats.hpp"
 #include "oops/oop.inline.hpp"
 #include "utilities/globalDefinitions.hpp"
--- a/src/hotspot/share/classfile/loaderConstraints.cpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/hotspot/share/classfile/loaderConstraints.cpp	Mon Oct 01 09:56:45 2018 +0100
@@ -23,8 +23,9 @@
  */
 
 #include "precompiled.hpp"
+#include "classfile/classLoaderData.inline.hpp"
+#include "classfile/classLoaderDataGraph.hpp"
 #include "classfile/dictionary.hpp"
-#include "classfile/classLoaderData.inline.hpp"
 #include "classfile/loaderConstraints.hpp"
 #include "logging/log.hpp"
 #include "memory/resourceArea.hpp"
--- a/src/hotspot/share/classfile/systemDictionary.cpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/hotspot/share/classfile/systemDictionary.cpp	Mon Oct 01 09:56:45 2018 +0100
@@ -29,6 +29,7 @@
 #include "classfile/classFileStream.hpp"
 #include "classfile/classLoader.hpp"
 #include "classfile/classLoaderData.inline.hpp"
+#include "classfile/classLoaderDataGraph.inline.hpp"
 #include "classfile/classLoaderExt.hpp"
 #include "classfile/dictionary.hpp"
 #include "classfile/javaClasses.inline.hpp"
--- a/src/hotspot/share/code/dependencyContext.cpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/hotspot/share/code/dependencyContext.cpp	Mon Oct 01 09:56:45 2018 +0100
@@ -218,18 +218,6 @@
   return marked;
 }
 
-void DependencyContext::wipe() {
-  assert_locked_or_safepoint(CodeCache_lock);
-  nmethodBucket* b = dependencies();
-  set_dependencies(NULL);
-  set_has_stale_entries(false);
-  while (b != NULL) {
-    nmethodBucket* next = b->next();
-    delete b;
-    b = next;
-  }
-}
-
 #ifndef PRODUCT
 void DependencyContext::print_dependent_nmethods(bool verbose) {
   int idx = 0;
--- a/src/hotspot/share/code/dependencyContext.hpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/hotspot/share/code/dependencyContext.hpp	Mon Oct 01 09:56:45 2018 +0100
@@ -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
@@ -141,10 +141,6 @@
 
   void expunge_stale_entries();
 
-  // Unsafe deallocation of nmethodBuckets. Used in IK::release_C_heap_structures
-  // to clean up the context possibly containing live entries pointing to unloaded nmethods.
-  void wipe();
-
 #ifndef PRODUCT
   void print_dependent_nmethods(bool verbose);
   bool is_dependent_nmethod(nmethod* nm);
--- a/src/hotspot/share/gc/cms/concurrentMarkSweepGeneration.cpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/hotspot/share/gc/cms/concurrentMarkSweepGeneration.cpp	Mon Oct 01 09:56:45 2018 +0100
@@ -23,7 +23,7 @@
  */
 
 #include "precompiled.hpp"
-#include "classfile/classLoaderData.hpp"
+#include "classfile/classLoaderDataGraph.hpp"
 #include "classfile/stringTable.hpp"
 #include "classfile/symbolTable.hpp"
 #include "classfile/systemDictionary.hpp"
--- a/src/hotspot/share/gc/g1/g1CollectedHeap.cpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/hotspot/share/gc/g1/g1CollectedHeap.cpp	Mon Oct 01 09:56:45 2018 +0100
@@ -23,6 +23,7 @@
  */
 
 #include "precompiled.hpp"
+#include "classfile/classLoaderDataGraph.hpp"
 #include "classfile/metadataOnStackMark.hpp"
 #include "classfile/stringTable.hpp"
 #include "code/codeCache.hpp"
--- a/src/hotspot/share/gc/g1/g1ConcurrentMark.cpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/hotspot/share/gc/g1/g1ConcurrentMark.cpp	Mon Oct 01 09:56:45 2018 +0100
@@ -23,7 +23,7 @@
  */
 
 #include "precompiled.hpp"
-#include "classfile/metadataOnStackMark.hpp"
+#include "classfile/classLoaderDataGraph.hpp"
 #include "code/codeCache.hpp"
 #include "gc/g1/g1BarrierSet.hpp"
 #include "gc/g1/g1CollectedHeap.inline.hpp"
--- a/src/hotspot/share/gc/g1/g1ConcurrentMarkThread.cpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/hotspot/share/gc/g1/g1ConcurrentMarkThread.cpp	Mon Oct 01 09:56:45 2018 +0100
@@ -23,7 +23,7 @@
  */
 
 #include "precompiled.hpp"
-#include "classfile/classLoaderData.hpp"
+#include "classfile/classLoaderDataGraph.hpp"
 #include "gc/g1/g1Analytics.hpp"
 #include "gc/g1/g1CollectedHeap.inline.hpp"
 #include "gc/g1/g1ConcurrentMark.inline.hpp"
--- a/src/hotspot/share/gc/g1/g1FullGCAdjustTask.cpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/hotspot/share/gc/g1/g1FullGCAdjustTask.cpp	Mon Oct 01 09:56:45 2018 +0100
@@ -23,6 +23,7 @@
  */
 
 #include "precompiled.hpp"
+#include "classfile/classLoaderDataGraph.hpp"
 #include "gc/g1/g1CollectedHeap.hpp"
 #include "gc/g1/g1ConcurrentMarkBitMap.inline.hpp"
 #include "gc/g1/g1FullCollector.hpp"
--- a/src/hotspot/share/gc/g1/g1FullGCMarkTask.cpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/hotspot/share/gc/g1/g1FullGCMarkTask.cpp	Mon Oct 01 09:56:45 2018 +0100
@@ -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
@@ -23,6 +23,7 @@
  */
 
 #include "precompiled.hpp"
+#include "classfile/classLoaderDataGraph.hpp"
 #include "gc/g1/g1CollectedHeap.hpp"
 #include "gc/g1/g1FullCollector.hpp"
 #include "gc/g1/g1FullGCMarker.hpp"
--- a/src/hotspot/share/gc/g1/g1RootProcessor.cpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/hotspot/share/gc/g1/g1RootProcessor.cpp	Mon Oct 01 09:56:45 2018 +0100
@@ -23,8 +23,8 @@
  */
 
 #include "precompiled.hpp"
-
 #include "aot/aotLoader.hpp"
+#include "classfile/classLoaderDataGraph.hpp"
 #include "classfile/stringTable.hpp"
 #include "classfile/systemDictionary.hpp"
 #include "code/codeCache.hpp"
--- a/src/hotspot/share/gc/parallel/pcTasks.cpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/hotspot/share/gc/parallel/pcTasks.cpp	Mon Oct 01 09:56:45 2018 +0100
@@ -24,6 +24,7 @@
 
 #include "precompiled.hpp"
 #include "aot/aotLoader.hpp"
+#include "classfile/classLoaderDataGraph.hpp"
 #include "classfile/systemDictionary.hpp"
 #include "code/codeCache.hpp"
 #include "gc/parallel/parallelScavengeHeap.hpp"
--- a/src/hotspot/share/gc/parallel/psMarkSweep.cpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/hotspot/share/gc/parallel/psMarkSweep.cpp	Mon Oct 01 09:56:45 2018 +0100
@@ -24,6 +24,7 @@
 
 #include "precompiled.hpp"
 #include "aot/aotLoader.hpp"
+#include "classfile/classLoaderDataGraph.hpp"
 #include "classfile/stringTable.hpp"
 #include "classfile/symbolTable.hpp"
 #include "classfile/systemDictionary.hpp"
--- a/src/hotspot/share/gc/parallel/psParallelCompact.cpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/hotspot/share/gc/parallel/psParallelCompact.cpp	Mon Oct 01 09:56:45 2018 +0100
@@ -24,6 +24,7 @@
 
 #include "precompiled.hpp"
 #include "aot/aotLoader.hpp"
+#include "classfile/classLoaderDataGraph.hpp"
 #include "classfile/javaClasses.inline.hpp"
 #include "classfile/stringTable.hpp"
 #include "classfile/symbolTable.hpp"
--- a/src/hotspot/share/gc/parallel/psTasks.cpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/hotspot/share/gc/parallel/psTasks.cpp	Mon Oct 01 09:56:45 2018 +0100
@@ -24,6 +24,7 @@
 
 #include "precompiled.hpp"
 #include "aot/aotLoader.hpp"
+#include "classfile/classLoaderDataGraph.hpp"
 #include "classfile/systemDictionary.hpp"
 #include "code/codeCache.hpp"
 #include "gc/parallel/gcTaskManager.hpp"
--- a/src/hotspot/share/gc/serial/genMarkSweep.cpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/hotspot/share/gc/serial/genMarkSweep.cpp	Mon Oct 01 09:56:45 2018 +0100
@@ -23,6 +23,7 @@
  */
 
 #include "precompiled.hpp"
+#include "classfile/classLoaderDataGraph.hpp"
 #include "classfile/javaClasses.hpp"
 #include "classfile/stringTable.hpp"
 #include "classfile/symbolTable.hpp"
--- a/src/hotspot/share/gc/shared/cardTableRS.cpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/hotspot/share/gc/shared/cardTableRS.cpp	Mon Oct 01 09:56:45 2018 +0100
@@ -23,6 +23,7 @@
  */
 
 #include "precompiled.hpp"
+#include "classfile/classLoaderDataGraph.hpp"
 #include "gc/shared/cardTableRS.hpp"
 #include "gc/shared/genCollectedHeap.hpp"
 #include "gc/shared/genOopClosures.hpp"
--- a/src/hotspot/share/gc/shared/genCollectedHeap.cpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/hotspot/share/gc/shared/genCollectedHeap.cpp	Mon Oct 01 09:56:45 2018 +0100
@@ -24,6 +24,7 @@
 
 #include "precompiled.hpp"
 #include "aot/aotLoader.hpp"
+#include "classfile/classLoaderDataGraph.hpp"
 #include "classfile/symbolTable.hpp"
 #include "classfile/stringTable.hpp"
 #include "classfile/systemDictionary.hpp"
--- a/src/hotspot/share/gc/shared/memAllocator.hpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/hotspot/share/gc/shared/memAllocator.hpp	Mon Oct 01 09:56:45 2018 +0100
@@ -34,9 +34,9 @@
 // These fascilities are used for allocating, and initializing newly allocated objects.
 
 class MemAllocator: StackObj {
+protected:
   class Allocation;
 
-protected:
   CollectedHeap* const _heap;
   Thread* const        _thread;
   Klass* const         _klass;
--- a/src/hotspot/share/gc/shared/parallelCleaning.hpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/hotspot/share/gc/shared/parallelCleaning.hpp	Mon Oct 01 09:56:45 2018 +0100
@@ -25,6 +25,7 @@
 #ifndef SHARE_VM_GC_SHARED_PARALLELCLEANING_HPP
 #define SHARE_VM_GC_SHARED_PARALLELCLEANING_HPP
 
+#include "classfile/classLoaderDataGraph.inline.hpp"
 #include "gc/shared/oopStorageParState.hpp"
 #include "gc/shared/stringdedup/stringDedup.hpp"
 #include "gc/shared/workgroup.hpp"
--- a/src/hotspot/share/gc/z/zRootsIterator.cpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/hotspot/share/gc/z/zRootsIterator.cpp	Mon Oct 01 09:56:45 2018 +0100
@@ -22,7 +22,7 @@
  */
 
 #include "precompiled.hpp"
-#include "classfile/classLoaderData.hpp"
+#include "classfile/classLoaderDataGraph.hpp"
 #include "classfile/stringTable.hpp"
 #include "classfile/systemDictionary.hpp"
 #include "code/codeCache.hpp"
--- a/src/hotspot/share/jfr/leakprofiler/chains/rootSetClosure.cpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/hotspot/share/jfr/leakprofiler/chains/rootSetClosure.cpp	Mon Oct 01 09:56:45 2018 +0100
@@ -24,7 +24,7 @@
 
 #include "precompiled.hpp"
 #include "aot/aotLoader.hpp"
-#include "classfile/classLoaderData.hpp"
+#include "classfile/classLoaderDataGraph.hpp"
 #include "classfile/stringTable.hpp"
 #include "classfile/systemDictionary.hpp"
 #include "gc/shared/strongRootsScope.hpp"
--- a/src/hotspot/share/jfr/leakprofiler/checkpoint/rootResolver.cpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/hotspot/share/jfr/leakprofiler/checkpoint/rootResolver.cpp	Mon Oct 01 09:56:45 2018 +0100
@@ -24,6 +24,7 @@
 
 #include "precompiled.hpp"
 #include "aot/aotLoader.hpp"
+#include "classfile/classLoaderDataGraph.hpp"
 #include "classfile/stringTable.hpp"
 #include "gc/shared/strongRootsScope.hpp"
 #include "jfr/leakprofiler/utilities/unifiedOop.hpp"
--- a/src/hotspot/share/jfr/leakprofiler/utilities/saveRestore.cpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/hotspot/share/jfr/leakprofiler/utilities/saveRestore.cpp	Mon Oct 01 09:56:45 2018 +0100
@@ -23,7 +23,7 @@
  */
 
 #include "precompiled.hpp"
-#include "classfile/classLoaderData.hpp"
+#include "classfile/classLoaderDataGraph.hpp"
 #include "jfr/leakprofiler/utilities/saveRestore.hpp"
 #include "oops/oop.inline.hpp"
 
--- a/src/hotspot/share/jfr/periodic/jfrModuleEvent.cpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/hotspot/share/jfr/periodic/jfrModuleEvent.cpp	Mon Oct 01 09:56:45 2018 +0100
@@ -23,7 +23,8 @@
  */
 
 #include "precompiled.hpp"
-#include "classfile/classLoaderData.hpp"
+#include "classfile/classLoaderData.inline.hpp"
+#include "classfile/classLoaderDataGraph.hpp"
 #include "classfile/moduleEntry.hpp"
 #include "classfile/packageEntry.hpp"
 #include "jfr/jfrEvents.hpp"
--- a/src/hotspot/share/jfr/periodic/jfrPeriodic.cpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/hotspot/share/jfr/periodic/jfrPeriodic.cpp	Mon Oct 01 09:56:45 2018 +0100
@@ -24,6 +24,7 @@
 
 #include "precompiled.hpp"
 #include "jvm.h"
+#include "classfile/classLoaderDataGraph.hpp"
 #include "classfile/classLoaderStats.hpp"
 #include "classfile/javaClasses.hpp"
 #include "code/codeCache.hpp"
--- a/src/hotspot/share/jfr/recorder/checkpoint/types/jfrTypeSet.cpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/hotspot/share/jfr/recorder/checkpoint/types/jfrTypeSet.cpp	Mon Oct 01 09:56:45 2018 +0100
@@ -23,7 +23,7 @@
  */
 
 #include "precompiled.hpp"
-#include "classfile/classLoaderData.inline.hpp"
+#include "classfile/classLoaderDataGraph.hpp"
 #include "classfile/javaClasses.inline.hpp"
 #include "classfile/moduleEntry.hpp"
 #include "classfile/packageEntry.hpp"
--- a/src/hotspot/share/memory/heapInspection.cpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/hotspot/share/memory/heapInspection.cpp	Mon Oct 01 09:56:45 2018 +0100
@@ -24,6 +24,7 @@
 
 #include "precompiled.hpp"
 #include "classfile/classLoaderData.inline.hpp"
+#include "classfile/classLoaderDataGraph.hpp"
 #include "classfile/moduleEntry.hpp"
 #include "classfile/systemDictionary.hpp"
 #include "gc/shared/collectedHeap.hpp"
--- a/src/hotspot/share/memory/metaspace.cpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/hotspot/share/memory/metaspace.cpp	Mon Oct 01 09:56:45 2018 +0100
@@ -23,8 +23,8 @@
  */
 
 #include "precompiled.hpp"
-
 #include "aot/aotLoader.hpp"
+#include "classfile/classLoaderDataGraph.hpp"
 #include "gc/shared/collectedHeap.hpp"
 #include "logging/log.hpp"
 #include "logging/logStream.hpp"
--- a/src/hotspot/share/memory/metaspaceShared.cpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/hotspot/share/memory/metaspaceShared.cpp	Mon Oct 01 09:56:45 2018 +0100
@@ -24,6 +24,7 @@
 
 #include "precompiled.hpp"
 #include "jvm.h"
+#include "classfile/classLoaderDataGraph.hpp"
 #include "classfile/classListParser.hpp"
 #include "classfile/classLoaderExt.hpp"
 #include "classfile/dictionary.hpp"
--- a/src/hotspot/share/memory/universe.cpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/hotspot/share/memory/universe.cpp	Mon Oct 01 09:56:45 2018 +0100
@@ -25,7 +25,7 @@
 #include "precompiled.hpp"
 #include "aot/aotLoader.hpp"
 #include "classfile/classLoader.hpp"
-#include "classfile/classLoaderData.hpp"
+#include "classfile/classLoaderDataGraph.hpp"
 #include "classfile/javaClasses.hpp"
 #include "classfile/stringTable.hpp"
 #include "classfile/systemDictionary.hpp"
--- a/src/hotspot/share/oops/instanceKlass.cpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/hotspot/share/oops/instanceKlass.cpp	Mon Oct 01 09:56:45 2018 +0100
@@ -686,15 +686,6 @@
   return Verifier::verify(this, should_verify_class(), THREAD);
 }
 
-
-// Used exclusively by the shared spaces dump mechanism to prevent
-// classes mapped into the shared regions in new VMs from appearing linked.
-
-void InstanceKlass::unlink_class() {
-  assert(is_linked(), "must be linked");
-  _init_state = loaded;
-}
-
 void InstanceKlass::link_class(TRAPS) {
   assert(is_loaded(), "must be loaded");
   if (!is_linked()) {
@@ -2300,10 +2291,12 @@
     return;
   }
 
-  // Unlink the class
-  if (is_linked()) {
-    unlink_class();
-  }
+  // Reset to the 'allocated' state to prevent any premature accessing to
+  // a shared class at runtime while the class is still being loaded and
+  // restored. A class' init_state is set to 'loaded' at runtime when it's
+  // being added to class hierarchy (see SystemDictionary:::add_to_hierarchy()).
+  _init_state = allocated;
+
   {
     MutexLocker ml(Compile_lock);
     init_implementor();
@@ -2350,6 +2343,10 @@
 }
 
 void InstanceKlass::restore_unshareable_info(ClassLoaderData* loader_data, Handle protection_domain, TRAPS) {
+  // SystemDictionary::add_to_hierarchy() sets the init_state to loaded
+  // before the InstanceKlass is added to the SystemDictionary. Make
+  // sure the current state is <loaded.
+  assert(!is_loaded(), "invalid init state");
   set_package(loader_data, CHECK);
   Klass::restore_unshareable_info(loader_data, protection_domain, CHECK);
 
@@ -2417,7 +2414,10 @@
 }
 #endif
 
-void InstanceKlass::notify_unload_class(InstanceKlass* ik) {
+void InstanceKlass::unload_class(InstanceKlass* ik) {
+  // Release dependencies.
+  ik->dependencies().remove_all_dependents();
+
   // notify the debugger
   if (JvmtiExport::should_post_class_unload()) {
     JvmtiExport::post_class_unload(ik);
@@ -2462,16 +2462,8 @@
     FreeHeap(jmeths);
   }
 
-  // Release dependencies.
-  // It is desirable to use DC::remove_all_dependents() here, but, unfortunately,
-  // it is not safe (see JDK-8143408). The problem is that the klass dependency
-  // context can contain live dependencies, since there's a race between nmethod &
-  // klass unloading. If the klass is dead when nmethod unloading happens, relevant
-  // dependencies aren't removed from the context associated with the class (see
-  // nmethod::flush_dependencies). It ends up during klass unloading as seemingly
-  // live dependencies pointing to unloaded nmethods and causes a crash in
-  // DC::remove_all_dependents() when it touches unloaded nmethod.
-  dependencies().wipe();
+  assert(_dep_context == DependencyContext::EMPTY,
+         "dependencies should already be cleaned");
 
 #if INCLUDE_JVMTI
   // Deallocate breakpoint records
--- a/src/hotspot/share/oops/instanceKlass.hpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/hotspot/share/oops/instanceKlass.hpp	Mon Oct 01 09:56:45 2018 +0100
@@ -542,7 +542,6 @@
   void initialize(TRAPS);
   void link_class(TRAPS);
   bool link_class_or_fail(TRAPS); // returns false on failure
-  void unlink_class();
   void rewrite_class(TRAPS);
   void link_methods(TRAPS);
   Method* class_initializer() const;
@@ -1180,7 +1179,7 @@
   bool on_stack() const { return _constants->on_stack(); }
 
   // callbacks for actions during class unloading
-  static void notify_unload_class(InstanceKlass* ik);
+  static void unload_class(InstanceKlass* ik);
   static void release_C_heap_structures(InstanceKlass* ik);
 
   // Naming
--- a/src/hotspot/share/oops/klassVtable.cpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/hotspot/share/oops/klassVtable.cpp	Mon Oct 01 09:56:45 2018 +0100
@@ -24,6 +24,7 @@
 
 #include "precompiled.hpp"
 #include "jvm.h"
+#include "classfile/classLoaderDataGraph.hpp"
 #include "classfile/javaClasses.hpp"
 #include "classfile/systemDictionary.hpp"
 #include "classfile/vmSymbols.hpp"
--- a/src/hotspot/share/oops/method.cpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/hotspot/share/oops/method.cpp	Mon Oct 01 09:56:45 2018 +0100
@@ -23,6 +23,7 @@
  */
 
 #include "precompiled.hpp"
+#include "classfile/classLoaderDataGraph.hpp"
 #include "classfile/metadataOnStackMark.hpp"
 #include "classfile/systemDictionary.hpp"
 #include "code/codeCache.hpp"
--- a/src/hotspot/share/prims/jvmtiEnvBase.cpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/hotspot/share/prims/jvmtiEnvBase.cpp	Mon Oct 01 09:56:45 2018 +0100
@@ -23,6 +23,7 @@
  */
 
 #include "precompiled.hpp"
+#include "classfile/classLoaderDataGraph.hpp"
 #include "classfile/systemDictionary.hpp"
 #include "jvmtifiles/jvmtiEnv.hpp"
 #include "memory/resourceArea.hpp"
--- a/src/hotspot/share/prims/jvmtiGetLoadedClasses.cpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/hotspot/share/prims/jvmtiGetLoadedClasses.cpp	Mon Oct 01 09:56:45 2018 +0100
@@ -23,8 +23,8 @@
  */
 
 #include "precompiled.hpp"
+#include "classfile/classLoaderDataGraph.hpp"
 #include "classfile/dictionary.hpp"
-#include "classfile/classLoaderData.inline.hpp"
 #include "classfile/systemDictionary.hpp"
 #include "gc/shared/collectedHeap.hpp"
 #include "memory/universe.hpp"
--- a/src/hotspot/share/prims/jvmtiRedefineClasses.cpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/hotspot/share/prims/jvmtiRedefineClasses.cpp	Mon Oct 01 09:56:45 2018 +0100
@@ -24,6 +24,7 @@
 
 #include "precompiled.hpp"
 #include "aot/aotLoader.hpp"
+#include "classfile/classLoaderDataGraph.hpp"
 #include "classfile/classFileStream.hpp"
 #include "classfile/metadataOnStackMark.hpp"
 #include "classfile/systemDictionary.hpp"
--- a/src/hotspot/share/prims/jvmtiTagMap.cpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/hotspot/share/prims/jvmtiTagMap.cpp	Mon Oct 01 09:56:45 2018 +0100
@@ -23,6 +23,7 @@
  */
 
 #include "precompiled.hpp"
+#include "classfile/classLoaderDataGraph.hpp"
 #include "classfile/javaClasses.inline.hpp"
 #include "classfile/symbolTable.hpp"
 #include "classfile/systemDictionary.hpp"
--- a/src/hotspot/share/prims/whitebox.cpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/hotspot/share/prims/whitebox.cpp	Mon Oct 01 09:56:45 2018 +0100
@@ -26,7 +26,7 @@
 
 #include <new>
 
-#include "classfile/classLoaderData.hpp"
+#include "classfile/classLoaderDataGraph.hpp"
 #include "classfile/modules.hpp"
 #include "classfile/protectionDomainCache.hpp"
 #include "classfile/stringTable.hpp"
--- a/src/hotspot/share/runtime/arguments.cpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/hotspot/share/runtime/arguments.cpp	Mon Oct 01 09:56:45 2018 +0100
@@ -542,6 +542,7 @@
   { "CreateMinidumpOnCrash",        JDK_Version::jdk(9),  JDK_Version::undefined(), JDK_Version::undefined() },
   { "MustCallLoadClassInternal",    JDK_Version::jdk(10), JDK_Version::jdk(11), JDK_Version::jdk(12) },
   { "UnsyncloadClass",              JDK_Version::jdk(10), JDK_Version::jdk(11), JDK_Version::jdk(12) },
+  { "TLABStats",                    JDK_Version::jdk(12), JDK_Version::undefined(), JDK_Version::undefined() },
 
   // -------------- Obsolete Flags - sorted by expired_in --------------
   { "CheckAssertionStatusDirectives",JDK_Version::undefined(), JDK_Version::jdk(11), JDK_Version::jdk(12) },
@@ -3850,6 +3851,10 @@
   UNSUPPORTED_OPTION(UseLargePages);
 #endif
 
+#if defined(AIX)
+  UNSUPPORTED_OPTION(AllocateHeapAt);
+#endif
+
   ArgumentsExt::report_unsupported_options();
 
 #ifndef PRODUCT
--- a/src/hotspot/share/runtime/biasedLocking.cpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/hotspot/share/runtime/biasedLocking.cpp	Mon Oct 01 09:56:45 2018 +0100
@@ -23,6 +23,7 @@
  */
 
 #include "precompiled.hpp"
+#include "classfile/classLoaderDataGraph.hpp"
 #include "jfr/jfrEvents.hpp"
 #include "jfr/support/jfrThreadId.hpp"
 #include "logging/log.hpp"
--- a/src/hotspot/share/runtime/compilationPolicy.cpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/hotspot/share/runtime/compilationPolicy.cpp	Mon Oct 01 09:56:45 2018 +0100
@@ -23,7 +23,7 @@
  */
 
 #include "precompiled.hpp"
-#include "classfile/classLoaderData.inline.hpp"
+#include "classfile/classLoaderDataGraph.inline.hpp"
 #include "code/compiledIC.hpp"
 #include "code/nmethod.hpp"
 #include "code/scopeDesc.hpp"
--- a/src/hotspot/share/runtime/java.cpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/hotspot/share/runtime/java.cpp	Mon Oct 01 09:56:45 2018 +0100
@@ -26,6 +26,7 @@
 #include "jvm.h"
 #include "aot/aotLoader.hpp"
 #include "classfile/classLoader.hpp"
+#include "classfile/classLoaderDataGraph.hpp"
 #include "classfile/stringTable.hpp"
 #include "classfile/systemDictionary.hpp"
 #include "code/codeCache.hpp"
--- a/src/hotspot/share/runtime/memprofiler.cpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/hotspot/share/runtime/memprofiler.cpp	Mon Oct 01 09:56:45 2018 +0100
@@ -23,7 +23,7 @@
  */
 
 #include "precompiled.hpp"
-#include "classfile/classLoaderData.inline.hpp"
+#include "classfile/classLoaderDataGraph.inline.hpp"
 #include "classfile/systemDictionary.hpp"
 #include "code/codeCache.hpp"
 #include "gc/shared/collectedHeap.inline.hpp"
--- a/src/hotspot/share/runtime/objectMonitor.cpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/hotspot/share/runtime/objectMonitor.cpp	Mon Oct 01 09:56:45 2018 +0100
@@ -110,7 +110,7 @@
 static int Knob_FixedSpin           = 0;
 static int Knob_PreSpin             = 10;      // 20-100 likely better
 
-static volatile int InitDone        = 0;
+DEBUG_ONLY(static volatile bool InitDone = false;)
 
 // -----------------------------------------------------------------------------
 // Theory of operations -- Monitors lists, thread residency, etc:
@@ -428,7 +428,7 @@
     return;
   }
 
-  DeferredInitialize();
+  assert(InitDone, "Unexpectedly not initialized");
 
   // We try one round of spinning *before* enqueueing Self.
   //
@@ -1102,7 +1102,7 @@
   assert(Self->is_Java_thread(), "Must be Java thread!");
   JavaThread *jt = (JavaThread *)THREAD;
 
-  DeferredInitialize();
+  assert(InitDone, "Unexpectedly not initialized");
 
   if (THREAD != _owner) {
     if (THREAD->is_lock_owned ((address)_owner)) {
@@ -1186,7 +1186,7 @@
   assert(Self->is_Java_thread(), "Must be Java thread!");
   JavaThread *jt = (JavaThread *)THREAD;
 
-  DeferredInitialize();
+  assert(InitDone, "Unexpectedly not initialized");
 
   // Throw IMSX or IEX.
   CHECK_OWNER();
@@ -1888,9 +1888,14 @@
 // be protected - like so many things - by the MonitorCache_lock.
 
 void ObjectMonitor::Initialize() {
-  static int InitializationCompleted = 0;
-  assert(InitializationCompleted == 0, "invariant");
-  InitializationCompleted = 1;
+  assert(!InitDone, "invariant");
+
+  if (!os::is_MP()) {
+    Knob_SpinLimit = 0;
+    Knob_PreSpin   = 0;
+    Knob_FixedSpin = -1;
+  }
+
   if (UsePerfData) {
     EXCEPTION_MARK;
 #define NEWPERFCOUNTER(n)                                                \
@@ -1913,26 +1918,6 @@
 #undef NEWPERFCOUNTER
 #undef NEWPERFVARIABLE
   }
+
+  DEBUG_ONLY(InitDone = true;)
 }
-
-void ObjectMonitor::DeferredInitialize() {
-  if (InitDone > 0) return;
-  if (Atomic::cmpxchg (-1, &InitDone, 0) != 0) {
-    while (InitDone != 1) /* empty */;
-    return;
-  }
-
-  // One-shot global initialization ...
-  // The initialization is idempotent, so we don't need locks.
-  // In the future consider doing this via os::init_2().
-
-  if (!os::is_MP()) {
-    Knob_SpinLimit = 0;
-    Knob_PreSpin   = 0;
-    Knob_FixedSpin = -1;
-  }
-
-  OrderAccess::fence();
-  InitDone = 1;
-}
-
--- a/src/hotspot/share/runtime/objectMonitor.hpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/hotspot/share/runtime/objectMonitor.hpp	Mon Oct 01 09:56:45 2018 +0100
@@ -302,7 +302,6 @@
 
  private:
   void      AddWaiter(ObjectWaiter * waiter);
-  static    void DeferredInitialize();
   void      INotify(Thread * Self);
   ObjectWaiter * DequeueWaiter();
   void      DequeueSpecificWaiter(ObjectWaiter * waiter);
--- a/src/hotspot/share/runtime/safepoint.cpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/hotspot/share/runtime/safepoint.cpp	Mon Oct 01 09:56:45 2018 +0100
@@ -23,7 +23,7 @@
  */
 
 #include "precompiled.hpp"
-#include "classfile/classLoaderData.inline.hpp"
+#include "classfile/classLoaderDataGraph.inline.hpp"
 #include "classfile/stringTable.hpp"
 #include "classfile/symbolTable.hpp"
 #include "classfile/systemDictionary.hpp"
--- a/src/hotspot/share/runtime/vmStructs.cpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/hotspot/share/runtime/vmStructs.cpp	Mon Oct 01 09:56:45 2018 +0100
@@ -29,6 +29,7 @@
 #include "ci/ciObjArrayKlass.hpp"
 #include "ci/ciSymbol.hpp"
 #include "classfile/compactHashtable.hpp"
+#include "classfile/classLoaderDataGraph.hpp"
 #include "classfile/dictionary.hpp"
 #include "classfile/javaClasses.hpp"
 #include "classfile/stringTable.hpp"
--- a/src/hotspot/share/runtime/vm_version.cpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/hotspot/share/runtime/vm_version.cpp	Mon Oct 01 09:56:45 2018 +0100
@@ -220,6 +220,8 @@
         #define HOTSPOT_BUILD_COMPILER "MS VC++ 14.0 (VS2015)"
       #elif _MSC_VER == 1912
         #define HOTSPOT_BUILD_COMPILER "MS VC++ 15.5 (VS2017)"
+      #elif _MSC_VER == 1913
+        #define HOTSPOT_BUILD_COMPILER "MS VC++ 15.6 (VS2017)"
       #else
         #define HOTSPOT_BUILD_COMPILER "unknown MS VC++:" XSTR(_MSC_VER)
       #endif
--- a/src/hotspot/share/services/heapDumper.cpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/hotspot/share/services/heapDumper.cpp	Mon Oct 01 09:56:45 2018 +0100
@@ -24,6 +24,8 @@
 
 #include "precompiled.hpp"
 #include "jvm.h"
+#include "classfile/classLoaderData.inline.hpp"
+#include "classfile/classLoaderDataGraph.hpp"
 #include "classfile/symbolTable.hpp"
 #include "classfile/systemDictionary.hpp"
 #include "classfile/vmSymbols.hpp"
--- a/src/hotspot/share/services/memBaseline.cpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/hotspot/share/services/memBaseline.cpp	Mon Oct 01 09:56:45 2018 +0100
@@ -23,7 +23,7 @@
  */
 #include "precompiled.hpp"
 
-#include "classfile/classLoaderData.inline.hpp"
+#include "classfile/classLoaderDataGraph.inline.hpp"
 #include "memory/allocation.hpp"
 #include "runtime/safepoint.hpp"
 #include "runtime/thread.inline.hpp"
--- a/src/java.base/share/classes/java/util/Arrays.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/java.base/share/classes/java/util/Arrays.java	Mon Oct 01 09:56:45 2018 +0100
@@ -28,6 +28,7 @@
 import jdk.internal.HotSpotIntrinsicCandidate;
 import jdk.internal.util.ArraysSupport;
 
+import java.io.Serializable;
 import java.lang.reflect.Array;
 import java.util.concurrent.ForkJoinPool;
 import java.util.function.BinaryOperator;
@@ -4288,21 +4289,41 @@
     // Misc
 
     /**
-     * Returns a fixed-size list backed by the specified array.  (Changes to
-     * the returned list "write through" to the array.)  This method acts
-     * as bridge between array-based and collection-based APIs, in
-     * combination with {@link Collection#toArray}.  The returned list is
-     * serializable and implements {@link RandomAccess}.
+     * Returns a fixed-size list backed by the specified array. Changes made to
+     * the array will be visible in the returned list, and changes made to the
+     * list will be visible in the array. The returned list is
+     * {@link Serializable} and implements {@link RandomAccess}.
+     *
+     * <p>The returned list implements the optional {@code Collection} methods, except
+     * those that would change the size of the returned list. Those methods leave
+     * the list unchanged and throw {@link UnsupportedOperationException}.
+     *
+     * @apiNote
+     * This method acts as bridge between array-based and collection-based
+     * APIs, in combination with {@link Collection#toArray}.
+     *
+     * <p>This method provides a way to wrap an existing array:
+     * <pre>{@code
+     *     Integer[] numbers = ...
+     *     ...
+     *     List<Integer> values = Arrays.asList(numbers);
+     * }</pre>
      *
      * <p>This method also provides a convenient way to create a fixed-size
      * list initialized to contain several elements:
-     * <pre>
-     *     List&lt;String&gt; stooges = Arrays.asList("Larry", "Moe", "Curly");
-     * </pre>
+     * <pre>{@code
+     *     List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");
+     * }</pre>
+     *
+     * <p><em>The list returned by this method is modifiable.</em>
+     * To create an unmodifiable list, use
+     * {@link Collections#unmodifiableList Collections.unmodifiableList}
+     * or <a href="List.html#unmodifiable">Unmodifiable Lists</a>.
      *
      * @param <T> the class of the objects in the array
      * @param a the array by which the list will be backed
      * @return a list view of the specified array
+     * @throws NullPointerException if the specified array is {@code null}
      */
     @SafeVarargs
     @SuppressWarnings("varargs")
--- a/src/java.base/share/classes/java/util/concurrent/CompletableFuture.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/java.base/share/classes/java/util/concurrent/CompletableFuture.java	Mon Oct 01 09:56:45 2018 +0100
@@ -957,17 +957,17 @@
     @SuppressWarnings("serial")
     static final class UniExceptionally<T> extends UniCompletion<T,T> {
         Function<? super Throwable, ? extends T> fn;
-        UniExceptionally(CompletableFuture<T> dep, CompletableFuture<T> src,
+        UniExceptionally(Executor executor,
+                         CompletableFuture<T> dep, CompletableFuture<T> src,
                          Function<? super Throwable, ? extends T> fn) {
-            super(null, dep, src); this.fn = fn;
+            super(executor, dep, src); this.fn = fn;
         }
-        final CompletableFuture<T> tryFire(int mode) { // never ASYNC
-            // assert mode != ASYNC;
+        final CompletableFuture<T> tryFire(int mode) {
             CompletableFuture<T> d; CompletableFuture<T> a;
             Object r; Function<? super Throwable, ? extends T> f;
             if ((d = dep) == null || (f = fn) == null
                 || (a = src) == null || (r = a.result) == null
-                || !d.uniExceptionally(r, f, this))
+                || !d.uniExceptionally(r, f, mode > 0 ? null : this))
                 return null;
             dep = null; src = null; fn = null;
             return d.postFire(a, mode);
@@ -980,11 +980,11 @@
         Throwable x;
         if (result == null) {
             try {
-                if (r instanceof AltResult && (x = ((AltResult)r).ex) != null) {
-                    if (c != null && !c.claim())
-                        return false;
+                if (c != null && !c.claim())
+                    return false;
+                if (r instanceof AltResult && (x = ((AltResult)r).ex) != null)
                     completeValue(f.apply(x));
-                } else
+                else
                     internalComplete(r);
             } catch (Throwable ex) {
                 completeThrowable(ex);
@@ -994,14 +994,88 @@
     }
 
     private CompletableFuture<T> uniExceptionallyStage(
-        Function<Throwable, ? extends T> f) {
+        Executor e, Function<Throwable, ? extends T> f) {
         if (f == null) throw new NullPointerException();
         CompletableFuture<T> d = newIncompleteFuture();
         Object r;
         if ((r = result) == null)
-            unipush(new UniExceptionally<T>(d, this, f));
+            unipush(new UniExceptionally<T>(e, d, this, f));
+        else if (e == null)
+            d.uniExceptionally(r, f, null);
+        else {
+            try {
+                e.execute(new UniExceptionally<T>(null, d, this, f));
+            } catch (Throwable ex) {
+                d.result = encodeThrowable(ex);
+            }
+        }
+        return d;
+    }
+
+    @SuppressWarnings("serial")
+    static final class UniComposeExceptionally<T> extends UniCompletion<T,T> {
+        Function<Throwable, ? extends CompletionStage<T>> fn;
+        UniComposeExceptionally(Executor executor, CompletableFuture<T> dep,
+                                CompletableFuture<T> src,
+                                Function<Throwable, ? extends CompletionStage<T>> fn) {
+            super(executor, dep, src); this.fn = fn;
+        }
+        final CompletableFuture<T> tryFire(int mode) {
+            CompletableFuture<T> d; CompletableFuture<T> a;
+            Function<Throwable, ? extends CompletionStage<T>> f;
+            Object r; Throwable x;
+            if ((d = dep) == null || (f = fn) == null
+                || (a = src) == null || (r = a.result) == null)
+                return null;
+            if (d.result == null) {
+                if ((r instanceof AltResult) &&
+                    (x = ((AltResult)r).ex) != null) {
+                    try {
+                        if (mode <= 0 && !claim())
+                            return null;
+                        CompletableFuture<T> g = f.apply(x).toCompletableFuture();
+                        if ((r = g.result) != null)
+                            d.completeRelay(r);
+                        else {
+                            g.unipush(new UniRelay<T,T>(d, g));
+                            if (d.result == null)
+                                return null;
+                        }
+                    } catch (Throwable ex) {
+                        d.completeThrowable(ex);
+                    }
+                }
+                else
+                    d.internalComplete(r);
+            }
+            dep = null; src = null; fn = null;
+            return d.postFire(a, mode);
+        }
+    }
+
+    private CompletableFuture<T> uniComposeExceptionallyStage(
+        Executor e, Function<Throwable, ? extends CompletionStage<T>> f) {
+        if (f == null) throw new NullPointerException();
+        CompletableFuture<T> d = newIncompleteFuture();
+        Object r, s; Throwable x;
+        if ((r = result) == null)
+            unipush(new UniComposeExceptionally<T>(e, d, this, f));
+        else if (!(r instanceof AltResult) || (x = ((AltResult)r).ex) == null)
+            d.internalComplete(r);
         else
-            d.uniExceptionally(r, f, null);
+            try {
+                if (e != null)
+                    e.execute(new UniComposeExceptionally<T>(null, d, this, f));
+                else {
+                    CompletableFuture<T> g = f.apply(x).toCompletableFuture();
+                    if ((s = g.result) != null)
+                        d.result = encodeRelay(s);
+                    else
+                        g.unipush(new UniRelay<T,T>(d, g));
+                }
+            } catch (Throwable ex) {
+                d.result = encodeThrowable(ex);
+            }
         return d;
     }
 
@@ -1093,7 +1167,7 @@
         Object r, s; Throwable x;
         if ((r = result) == null)
             unipush(new UniCompose<T,V>(e, d, this, f));
-        else if (e == null) {
+        else {
             if (r instanceof AltResult) {
                 if ((x = ((AltResult)r).ex) != null) {
                     d.result = encodeThrowable(x, r);
@@ -1102,23 +1176,20 @@
                 r = null;
             }
             try {
-                @SuppressWarnings("unchecked") T t = (T) r;
-                CompletableFuture<V> g = f.apply(t).toCompletableFuture();
-                if ((s = g.result) != null)
-                    d.result = encodeRelay(s);
+                if (e != null)
+                    e.execute(new UniCompose<T,V>(null, d, this, f));
                 else {
-                    g.unipush(new UniRelay<V,V>(d, g));
+                    @SuppressWarnings("unchecked") T t = (T) r;
+                    CompletableFuture<V> g = f.apply(t).toCompletableFuture();
+                    if ((s = g.result) != null)
+                        d.result = encodeRelay(s);
+                    else
+                        g.unipush(new UniRelay<V,V>(d, g));
                 }
             } catch (Throwable ex) {
                 d.result = encodeThrowable(ex);
             }
         }
-        else
-            try {
-                e.execute(new UniCompose<T,V>(null, d, this, f));
-            } catch (Throwable ex) {
-                d.result = encodeThrowable(ex);
-            }
         return d;
     }
 
@@ -1898,7 +1969,7 @@
      * Creates a new complete CompletableFuture with given encoded result.
      */
     CompletableFuture(Object r) {
-        this.result = r;
+        RESULT.setRelease(this, r);
     }
 
     /**
@@ -2285,28 +2356,36 @@
         return this;
     }
 
-    // not in interface CompletionStage
-
-    /**
-     * Returns a new CompletableFuture that is completed when this
-     * CompletableFuture completes, with the result of the given
-     * function of the exception triggering this CompletableFuture's
-     * completion when it completes exceptionally; otherwise, if this
-     * CompletableFuture completes normally, then the returned
-     * CompletableFuture also completes normally with the same value.
-     * Note: More flexible versions of this functionality are
-     * available using methods {@code whenComplete} and {@code handle}.
-     *
-     * @param fn the function to use to compute the value of the
-     * returned CompletableFuture if this CompletableFuture completed
-     * exceptionally
-     * @return the new CompletableFuture
-     */
     public CompletableFuture<T> exceptionally(
         Function<Throwable, ? extends T> fn) {
-        return uniExceptionallyStage(fn);
+        return uniExceptionallyStage(null, fn);
     }
 
+    public CompletableFuture<T> exceptionallyAsync(
+        Function<Throwable, ? extends T> fn) {
+        return uniExceptionallyStage(defaultExecutor(), fn);
+    }
+
+    public CompletableFuture<T> exceptionallyAsync(
+        Function<Throwable, ? extends T> fn, Executor executor) {
+        return uniExceptionallyStage(screenExecutor(executor), fn);
+    }
+
+    public CompletableFuture<T> exceptionallyCompose(
+        Function<Throwable, ? extends CompletionStage<T>> fn) {
+        return uniComposeExceptionallyStage(null, fn);
+    }
+
+    public CompletableFuture<T> exceptionallyComposeAsync(
+        Function<Throwable, ? extends CompletionStage<T>> fn) {
+        return uniComposeExceptionallyStage(defaultExecutor(), fn);
+    }
+
+    public CompletableFuture<T> exceptionallyComposeAsync(
+        Function<Throwable, ? extends CompletionStage<T>> fn,
+        Executor executor) {
+        return uniComposeExceptionallyStage(screenExecutor(executor), fn);
+    }
 
     /* ------------- Arbitrary-arity constructions -------------- */
 
--- a/src/java.base/share/classes/java/util/concurrent/CompletionStage.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/java.base/share/classes/java/util/concurrent/CompletionStage.java	Mon Oct 01 09:56:45 2018 +0100
@@ -851,6 +851,130 @@
         (Function<Throwable, ? extends T> fn);
 
     /**
+     * Returns a new CompletionStage that, when this stage completes
+     * exceptionally, is executed with this stage's exception as the
+     * argument to the supplied function, using this stage's default
+     * asynchronous execution facility.  Otherwise, if this stage
+     * completes normally, then the returned stage also completes
+     * normally with the same value.
+     *
+     * @implSpec The default implementation invokes {@link #handle},
+     * relaying to {@link #handleAsync} on exception, then {@link
+     * #thenCompose} for result.
+     *
+     * @param fn the function to use to compute the value of the
+     * returned CompletionStage if this CompletionStage completed
+     * exceptionally
+     * @return the new CompletionStage
+     * @since 12
+     */
+    public default CompletionStage<T> exceptionallyAsync
+        (Function<Throwable, ? extends T> fn) {
+        return handle((r, ex) -> (ex == null)
+                      ? this
+                      : this.<T>handleAsync((r1, ex1) -> fn.apply(ex1)))
+            .thenCompose(Function.identity());
+    }
+
+    /**
+     * Returns a new CompletionStage that, when this stage completes
+     * exceptionally, is executed with this stage's exception as the
+     * argument to the supplied function, using the supplied Executor.
+     * Otherwise, if this stage completes normally, then the returned
+     * stage also completes normally with the same value.
+     *
+     * @implSpec The default implementation invokes {@link #handle},
+     * relaying to {@link #handleAsync} on exception, then {@link
+     * #thenCompose} for result.
+     *
+     * @param fn the function to use to compute the value of the
+     * returned CompletionStage if this CompletionStage completed
+     * exceptionally
+     * @param executor the executor to use for asynchronous execution
+     * @return the new CompletionStage
+     * @since 12
+     */
+    public default CompletionStage<T> exceptionallyAsync
+        (Function<Throwable, ? extends T> fn, Executor executor) {
+        return handle((r, ex) -> (ex == null)
+                      ? this
+                      : this.<T>handleAsync((r1, ex1) -> fn.apply(ex1), executor))
+            .thenCompose(Function.identity());
+    }
+
+    /**
+     * Returns a new CompletionStage that, when this stage completes
+     * exceptionally, is composed using the results of the supplied
+     * function applied to this stage's exception.
+     *
+     * @implSpec The default implementation invokes {@link #handle},
+     * invoking the given function on exception, then {@link
+     * #thenCompose} for result.
+     *
+     * @param fn the function to use to compute the returned
+     * CompletionStage if this CompletionStage completed exceptionally
+     * @return the new CompletionStage
+     * @since 12
+     */
+    public default CompletionStage<T> exceptionallyCompose
+        (Function<Throwable, ? extends CompletionStage<T>> fn) {
+        return handle((r, ex) -> (ex == null)
+                      ? this
+                      : fn.apply(ex))
+            .thenCompose(Function.identity());
+    }
+
+    /**
+     * Returns a new CompletionStage that, when this stage completes
+     * exceptionally, is composed using the results of the supplied
+     * function applied to this stage's exception, using this stage's
+     * default asynchronous execution facility.
+     *
+     * @implSpec The default implementation invokes {@link #handle},
+     * relaying to {@link #handleAsync} on exception, then {@link
+     * #thenCompose} for result.
+     *
+     * @param fn the function to use to compute the returned
+     * CompletionStage if this CompletionStage completed exceptionally
+     * @return the new CompletionStage
+     * @since 12
+     */
+    public default CompletionStage<T> exceptionallyComposeAsync
+        (Function<Throwable, ? extends CompletionStage<T>> fn) {
+        return handle((r, ex) -> (ex == null)
+                      ? this
+                      : this.handleAsync((r1, ex1) -> fn.apply(ex1))
+                        .thenCompose(Function.identity()))
+            .thenCompose(Function.identity());
+    }
+
+    /**
+     * Returns a new CompletionStage that, when this stage completes
+     * exceptionally, is composed using the results of the supplied
+     * function applied to this stage's exception, using the
+     * supplied Executor.
+     *
+     * @implSpec The default implementation invokes {@link #handle},
+     * relaying to {@link #handleAsync} on exception, then {@link
+     * #thenCompose} for result.
+     *
+     * @param fn the function to use to compute the returned
+     * CompletionStage if this CompletionStage completed exceptionally
+     * @param executor the executor to use for asynchronous execution
+     * @return the new CompletionStage
+     * @since 12
+     */
+    public default CompletionStage<T> exceptionallyComposeAsync
+        (Function<Throwable, ? extends CompletionStage<T>> fn,
+         Executor executor) {
+        return handle((r, ex) -> (ex == null)
+                      ? this
+                      : this.handleAsync((r1, ex1) -> fn.apply(ex1), executor)
+                        .thenCompose(Function.identity()))
+            .thenCompose(Function.identity());
+    }
+
+    /**
      * Returns a {@link CompletableFuture} maintaining the same
      * completion properties as this stage. If this stage is already a
      * CompletableFuture, this method may return this stage itself.
--- a/src/java.base/share/classes/module-info.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/java.base/share/classes/module-info.java	Mon Oct 01 09:56:45 2018 +0100
@@ -234,7 +234,6 @@
         jdk.jconsole,
         java.net.http;
     exports sun.net.www to
-        java.desktop,
         java.net.http,
         jdk.jartool;
     exports sun.net.www.protocol.http to
--- a/src/java.base/share/lib/security/default.policy	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/java.base/share/lib/security/default.policy	Mon Oct 01 09:56:45 2018 +0100
@@ -140,10 +140,6 @@
     permission java.io.FilePermission "<<ALL FILES>>", "read";
 };
 
-grant codeBase "jrt:/jdk.desktop" {
-    permission java.lang.RuntimePermission "accessClassInPackage.com.sun.awt";
-};
-
 grant codeBase "jrt:/jdk.dynalink" {
     permission java.security.AllPermission;
 };
--- a/src/java.base/share/native/libjli/args.c	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/java.base/share/native/libjli/args.c	Mon Oct 01 09:56:45 2018 +0100
@@ -263,6 +263,8 @@
                 }
                 JLI_List_addSubstring(pctx->parts, anchor, nextc - anchor);
                 pctx->state = IN_ESCAPE;
+                // anchor after backslash character
+                anchor = nextc + 1;
                 break;
             case '\'':
             case '"':
--- a/src/java.base/windows/native/libjava/java_props_md.c	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/java.base/windows/native/libjava/java_props_md.c	Mon Oct 01 09:56:45 2018 +0100
@@ -170,6 +170,10 @@
         return NULL;
     }
 
+    for (index = 0; index < 5; index++) {
+        elems[index] = NULL;
+    }
+
     if (SetupI18nProps(MAKELCID(langID, SORT_DEFAULT),
                    &(elems[0]), &(elems[1]), &(elems[2]), &(elems[3]), &(elems[4]))) {
 
@@ -183,15 +187,17 @@
                 strcat(ret, elems[index]);
             }
         }
-
-        for (index = 0; index < 5; index++) {
-            free(elems[index]);
-        }
     } else {
         free(ret);
         ret = NULL;
     }
 
+    for (index = 0; index < 5; index++) {
+        if (elems[index] != NULL) {
+            free(elems[index]);
+        }
+    }
+
     return ret;
 }
 
--- a/src/java.desktop/macosx/classes/com/apple/eawt/_AppMenuBarHandler.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/java.desktop/macosx/classes/com/apple/eawt/_AppMenuBarHandler.java	Mon Oct 01 09:56:45 2018 +0100
@@ -46,6 +46,7 @@
 
     private static native void nativeSetMenuState(final int menu, final boolean visible, final boolean enabled);
     private static native void nativeSetDefaultMenuBar(final long menuBarPeer);
+    private static native void nativeActivateDefaultMenuBar(final long menuBarPeer);
 
     static final _AppMenuBarHandler instance = new _AppMenuBarHandler();
     static _AppMenuBarHandler getInstance() {
@@ -78,26 +79,18 @@
 
     void setDefaultMenuBar(final JMenuBar menuBar) {
         installDefaultMenuBar(menuBar);
-        if (menuBar == null) {
-            return;
-        }
+    }
 
+    static boolean isMenuBarActivationNeeded() {
         // scan the current frames, and see if any are foreground
         final Frame[] frames = Frame.getFrames();
         for (final Frame frame : frames) {
             if (frame.isVisible() && !isFrameMinimized(frame)) {
-                return;
+                return false;
             }
         }
 
-        // if we have no foreground frames, then we have to "kick" the menubar
-        final JFrame pingFrame = new JFrame();
-        pingFrame.getRootPane().putClientProperty("Window.alpha", Float.valueOf(0.0f));
-        pingFrame.setUndecorated(true);
-        pingFrame.setVisible(true);
-        pingFrame.toFront();
-        pingFrame.setVisible(false);
-        pingFrame.dispose();
+        return true;
     }
 
     static boolean isFrameMinimized(final Frame frame) {
@@ -150,6 +143,11 @@
 
         // grab the pointer to the CMenuBar, and retain it in native
         ((CMenuBar) peer).execute(_AppMenuBarHandler::nativeSetDefaultMenuBar);
+
+        // if there is no currently active frame, install the default menu bar in the application main menu
+        if (isMenuBarActivationNeeded()) {
+            ((CMenuBar) peer).execute(_AppMenuBarHandler::nativeActivateDefaultMenuBar);
+        }
     }
 
     void setAboutMenuItemVisible(final boolean present) {
--- a/src/java.desktop/macosx/classes/sun/font/CStrike.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/java.desktop/macosx/classes/sun/font/CStrike.java	Mon Oct 01 09:56:45 2018 +0100
@@ -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
@@ -506,12 +506,6 @@
         private SparseBitShiftingTwoLayerArray secondLayerCache;
         private HashMap<Integer, Float> generalCache;
 
-        // Empty non private constructor was added because access to this
-        // class shouldn't be emulated by a synthetic accessor method.
-        GlyphAdvanceCache() {
-            super();
-        }
-
         public synchronized float get(final int index) {
             if (index < 0) {
                 if (-index < SECOND_LAYER_SIZE) {
--- a/src/java.desktop/macosx/classes/sun/lwawt/LWButtonPeer.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/java.desktop/macosx/classes/sun/lwawt/LWButtonPeer.java	Mon Oct 01 09:56:45 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2013, 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
@@ -81,12 +81,6 @@
     @SuppressWarnings("serial")// Safe: outer class is non-serializable.
     private final class JButtonDelegate extends JButton {
 
-        // Empty non private constructor was added because access to this
-        // class shouldn't be emulated by a synthetic accessor method.
-        JButtonDelegate() {
-            super();
-        }
-
         @Override
         public boolean hasFocus() {
             return getTarget().hasFocus();
--- a/src/java.desktop/macosx/classes/sun/lwawt/LWChoicePeer.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/java.desktop/macosx/classes/sun/lwawt/LWChoicePeer.java	Mon Oct 01 09:56:45 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2013, 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
@@ -135,12 +135,6 @@
     @SuppressWarnings("serial")// Safe: outer class is non-serializable.
     private final class JComboBoxDelegate extends JComboBox<String> {
 
-        // Empty non private constructor was added because access to this
-        // class shouldn't be emulated by a synthetic accessor method.
-        JComboBoxDelegate() {
-            super();
-        }
-
         @Override
         public boolean hasFocus() {
             return getTarget().hasFocus();
--- a/src/java.desktop/macosx/classes/sun/lwawt/LWComponentPeer.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/java.desktop/macosx/classes/sun/lwawt/LWComponentPeer.java	Mon Oct 01 09:56:45 2018 +0100
@@ -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
@@ -159,12 +159,6 @@
             enableEvents(0xFFFFFFFF);
         }
 
-        // Empty non private constructor was added because access to this
-        // class shouldn't be emulated by a synthetic accessor method.
-        DelegateContainer() {
-            super();
-        }
-
         @Override
         public boolean isLightweight() {
             return false;
--- a/src/java.desktop/macosx/classes/sun/lwawt/LWTextAreaPeer.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/java.desktop/macosx/classes/sun/lwawt/LWTextAreaPeer.java	Mon Oct 01 09:56:45 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2015, 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
@@ -219,12 +219,6 @@
 
         private final class JTextAreaDelegate extends JTextArea {
 
-            // Empty non private constructor was added because access to this
-            // class shouldn't be emulated by a synthetic accessor method.
-            JTextAreaDelegate() {
-                super();
-            }
-
             @Override
             public void replaceSelection(String content) {
                 getDocument().removeDocumentListener(LWTextAreaPeer.this);
--- a/src/java.desktop/macosx/classes/sun/lwawt/LWTextFieldPeer.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/java.desktop/macosx/classes/sun/lwawt/LWTextFieldPeer.java	Mon Oct 01 09:56:45 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2013, 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
@@ -122,12 +122,6 @@
     @SuppressWarnings("serial")// Safe: outer class is non-serializable.
     private final class JPasswordFieldDelegate extends JPasswordField {
 
-        // Empty non private constructor was added because access to this
-        // class shouldn't be emulated by a synthetic accessor method.
-        JPasswordFieldDelegate() {
-            super();
-        }
-
         @Override
         public void replaceSelection(String content) {
             getDocument().removeDocumentListener(LWTextFieldPeer.this);
--- a/src/java.desktop/macosx/classes/sun/lwawt/macosx/CEmbeddedFrame.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/java.desktop/macosx/classes/sun/lwawt/macosx/CEmbeddedFrame.java	Mon Oct 01 09:56:45 2018 +0100
@@ -165,8 +165,6 @@
                         : this;
             }
         }
-        // ignore focus "lost" native request as it may mistakenly
-        // deactivate active window (see 8001161)
         if (globalFocusedWindow == this) {
             responder.handleWindowFocusEvent(parentWindowActive, null);
         }
@@ -181,4 +179,19 @@
         // another window.
         return globalFocusedWindow != null ? !globalFocusedWindow.isParentWindowActive() : true;
     }
+
+    @Override
+    public void synthesizeWindowActivation(boolean doActivate) {
+        if (isParentWindowActive() != doActivate) {
+            handleWindowFocusEvent(doActivate);
+        }
+    }
+
+    public static void updateGlobalFocusedWindow(CEmbeddedFrame newGlobalFocusedWindow) {
+        synchronized (classLock) {
+            if (newGlobalFocusedWindow.isParentWindowActive()) {
+                globalFocusedWindow = newGlobalFocusedWindow;
+            }
+        }
+    }
 }
--- a/src/java.desktop/macosx/classes/sun/lwawt/macosx/CPlatformEmbeddedFrame.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/java.desktop/macosx/classes/sun/lwawt/macosx/CPlatformEmbeddedFrame.java	Mon Oct 01 09:56:45 2018 +0100
@@ -147,6 +147,8 @@
 
     @Override
     public boolean requestWindowFocus() {
+        CEmbeddedFrame.updateGlobalFocusedWindow(target);
+        target.synthesizeWindowActivation(true);
         return true;
     }
 
--- a/src/java.desktop/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/java.desktop/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java	Mon Oct 01 09:56:45 2018 +0100
@@ -1205,17 +1205,27 @@
     }
 
     private void orderAboveSiblings() {
-        // Recursively pop up the windows from the very bottom, (i.e. root owner) so that
-        // the windows are ordered above their nearest owner; ancestors of the window,
-        // which is going to become 'main window', are placed above their siblings.
         CPlatformWindow rootOwner = getRootOwner();
-        if (rootOwner.isVisible() && !rootOwner.isIconified()) {
-            rootOwner.execute(CWrapper.NSWindow::orderFront);
-        }
+
         // Do not order child windows of iconified owner.
         if (!rootOwner.isIconified()) {
             final WindowAccessor windowAccessor = AWTAccessor.getWindowAccessor();
-            orderAboveSiblingsImpl(windowAccessor.getOwnedWindows(rootOwner.target));
+            Window[] windows = windowAccessor.getOwnedWindows(rootOwner.target);
+
+            // No need to order windows if it doesn't own other windows and hence return
+            if (windows.length == 0) {
+                return;
+            }
+
+            // Recursively pop up the windows from the very bottom, (i.e. root owner) so that
+            // the windows are ordered above their nearest owner; ancestors of the window,
+            // which is going to become 'main window', are placed above their siblings.
+            if (rootOwner.isVisible()) {
+                rootOwner.execute(CWrapper.NSWindow::orderFront);
+            }
+
+            // Order child windows.
+            orderAboveSiblingsImpl(windows);
         }
     }
 
@@ -1276,6 +1286,21 @@
         }
     }
 
+    private Window getOwnerFrameOrDialog(Window window) {
+        Window owner = window.getOwner();
+        while (owner != null && !(owner instanceof Frame || owner instanceof Dialog)) {
+            owner = owner.getOwner();
+        }
+        return owner;
+    }
+
+    private boolean isSimpleWindowOwnedByEmbeddedFrame() {
+        if (peer != null && peer.isSimpleWindow()) {
+            return (getOwnerFrameOrDialog(target) instanceof CEmbeddedFrame);
+        }
+        return false;
+    }
+
     // ----------------------------------------------------------------------
     //                          NATIVE CALLBACKS
     // ----------------------------------------------------------------------
--- a/src/java.desktop/macosx/native/libawt_lwawt/awt/AWTView.m	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/java.desktop/macosx/native/libawt_lwawt/awt/AWTView.m	Mon Oct 01 09:56:45 2018 +0100
@@ -537,10 +537,14 @@
 }
 
 -(BOOL) isCodePointInUnicodeBlockNeedingIMEvent: (unichar) codePoint {
-    if (((codePoint >= 0x3000) && (codePoint <= 0x303F)) ||
+    if ((codePoint == 0x0024) || (codePoint == 0x00A3) ||
+        (codePoint == 0x00A5) ||
+        ((codePoint >= 0x20A3) && (codePoint <= 0x20BF)) ||
+	((codePoint >= 0x3000) && (codePoint <= 0x303F)) ||
         ((codePoint >= 0xFF00) && (codePoint <= 0xFFEF))) {
         // Code point is in 'CJK Symbols and Punctuation' or
-        // 'Halfwidth and Fullwidth Forms' Unicode block.
+        // 'Halfwidth and Fullwidth Forms' Unicode block or
+	// currency symbols unicode
         return YES;
     }
     return NO;
--- a/src/java.desktop/macosx/native/libawt_lwawt/awt/AWTWindow.m	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/java.desktop/macosx/native/libawt_lwawt/awt/AWTWindow.m	Mon Oct 01 09:56:45 2018 +0100
@@ -477,6 +477,21 @@
     return isBlocked;
 }
 
+// Test whether window is simple window and owned by embedded frame
+- (BOOL) isSimpleWindowOwnedByEmbeddedFrame {
+    BOOL isSimpleWindowOwnedByEmbeddedFrame = NO;
+
+    JNIEnv *env = [ThreadUtilities getJNIEnv];
+    jobject platformWindow = [self.javaPlatformWindow jObjectWithEnv:env];
+    if (platformWindow != NULL) {
+        static JNF_MEMBER_CACHE(jm_isBlocked, jc_CPlatformWindow, "isSimpleWindowOwnedByEmbeddedFrame", "()Z");
+        isSimpleWindowOwnedByEmbeddedFrame = JNFCallBooleanMethod(env, platformWindow, jm_isBlocked) == JNI_TRUE ? YES : NO;
+        (*env)->DeleteLocalRef(env, platformWindow);
+    }
+
+    return isSimpleWindowOwnedByEmbeddedFrame;
+}
+
 // Tests whether the corresponding Java platform window is visible or not
 + (BOOL) isJavaPlatformWindowVisible:(NSWindow *)window {
     BOOL isVisible = NO;
@@ -543,7 +558,7 @@
 // NSWindow overrides
 - (BOOL) canBecomeKeyWindow {
 AWT_ASSERT_APPKIT_THREAD;
-    return self.isEnabled && IS(self.styleBits, SHOULD_BECOME_KEY);
+    return self.isEnabled && (IS(self.styleBits, SHOULD_BECOME_KEY) || [self isSimpleWindowOwnedByEmbeddedFrame]);
 }
 
 - (BOOL) canBecomeMainWindow {
--- a/src/java.desktop/macosx/native/libawt_lwawt/awt/ApplicationDelegate.m	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/java.desktop/macosx/native/libawt_lwawt/awt/ApplicationDelegate.m	Mon Oct 01 09:56:45 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2016, 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
@@ -35,10 +35,10 @@
 #import <JavaNativeFoundation/JavaNativeFoundation.h>
 
 #import "CPopupMenu.h"
+#import "CMenuBar.h"
 #import "ThreadUtilities.h"
 #import "NSApplicationAWT.h"
 
-
 #pragma mark App Menu helpers
 
 // The following is a AWT convention?
@@ -201,11 +201,11 @@
 
     self.fPreferencesMenu = (NSMenuItem*)[appMenu itemWithTag:PREFERENCES_TAG];
     self.fAboutMenu = (NSMenuItem*)[appMenu itemAtIndex:0];
-    
+
     NSDockTile *dockTile = [NSApp dockTile];
     self.fProgressIndicator = [[NSProgressIndicator alloc]
                                 initWithFrame:NSMakeRect(3.f, 0.f, dockTile.size.width - 6.f, 20.f)];
-    
+
     [fProgressIndicator setStyle:NSProgressIndicatorBarStyle];
     [fProgressIndicator setIndeterminate:NO];
     [[dockTile contentView] addSubview:fProgressIndicator];
@@ -824,3 +824,23 @@
 
 JNF_COCOA_EXIT(env);
 }
+
+/*
+ * Class:     com_apple_eawt__AppMenuBarHandler
+ * Method:    nativeActivateDefaultMenuBar
+ * Signature: (J)V
+ */
+JNIEXPORT void JNICALL Java_com_apple_eawt__1AppMenuBarHandler_nativeActivateDefaultMenuBar
+(JNIEnv *env, jclass clz, jlong cMenuBarPtr)
+{
+JNF_COCOA_ENTER(env);
+
+    CMenuBar *menu = (CMenuBar *)jlong_to_ptr(cMenuBarPtr);
+    [ThreadUtilities performOnMainThreadWaiting:NO block:^(){
+        if (menu) {
+            [CMenuBar activate:menu modallyDisabled:NO];
+        }
+    }];
+
+JNF_COCOA_EXIT(env);
+}
--- a/src/java.desktop/share/classes/com/sun/awt/SecurityWarning.java	Wed Sep 26 18:11:00 2018 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,172 +0,0 @@
-/*
- * Copyright (c) 2008, 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.
- */
-
-package com.sun.awt;
-
-import java.awt.*;
-import java.awt.geom.*;
-
-import sun.awt.AWTAccessor;
-
-
-/**
- * Security Warning control interface.
- *
- * This class provides a couple of methods that help a developer relocate
- * the AWT security warning to an appropriate position relative to the current
- * window size. A "top-level window" is an instance of the {@code Window}
- * class (or its descendant, such as {@code JFrame}). The security warning
- * is applied to all windows created by an untrusted code. All such windows
- * have a non-null "warning string" (see {@link Window#getWarningString()}).
- * <p>
- * <b>WARNING</b>: This class is an implementation detail and only meant
- * for limited use outside of the core platform. This API may change
- * drastically between update release, and it may even be
- * removed or be moved to some other packages or classes.
- *
- * @deprecated This class is deprecated, no replacement.
- */
-@Deprecated(since = "11", forRemoval = true)
-public final class SecurityWarning {
-
-    /**
-     * The SecurityWarning class should not be instantiated
-     */
-    private SecurityWarning() {
-    }
-
-    /**
-     * Gets the size of the security warning.
-     *
-     * The returned value is not valid until the peer has been created. Before
-     * invoking this method a developer must call the {@link Window#pack()},
-     * {@link Window#setVisible}, or some other method that creates the peer.
-     *
-     * @param window the window to get the security warning size for
-     *
-     * @throws NullPointerException if the window argument is null
-     * @throws IllegalArgumentException if the window is trusted (i.e.
-     * the {@code getWarningString()} returns null)
-     */
-    public static Dimension getSize(Window window) {
-        if (window == null) {
-            throw new NullPointerException(
-                    "The window argument should not be null.");
-        }
-        if (window.getWarningString() == null) {
-            throw new IllegalArgumentException(
-                    "The window must have a non-null warning string.");
-        }
-        // We don't check for a non-null peer since it may be destroyed
-        // after assigning a valid value to the security warning size.
-
-        return AWTAccessor.getWindowAccessor().getSecurityWarningSize(window);
-    }
-
-    /**
-     * Sets the position of the security warning.
-     * <p>
-     * The {@code alignmentX} and {@code alignmentY} arguments specify the
-     * origin of the coordinate system used to calculate the position of the
-     * security warning. The values must be in the range [0.0f...1.0f].  The
-     * {@code 0.0f} value represents the left (top) edge of the rectangular
-     * bounds of the window. The {@code 1.0f} value represents the right
-     * (bottom) edge of the bounds. Whenever the size of the window changes,
-     * the origin of the coordinate system gets relocated accordingly. For
-     * convenience a developer may use the {@code Component.*_ALIGNMENT}
-     * constants to pass predefined values for these arguments.
-     * <p>
-     * The {@code point} argument specifies the location of the security
-     * warning in the coordinate system described above. If both {@code x} and
-     * {@code y} coordinates of the point are equal to zero, the warning will
-     * be located right in the origin of the coordinate system. On the other
-     * hand, if both {@code alignmentX} and {@code alignmentY} are equal to
-     * zero (i.e. the origin of the coordinate system is placed at the top-left
-     * corner of the window), then the {@code point} argument represents the
-     * absolute location of the security warning relative to the location of
-     * the window. The "absolute" in this case means that the position of the
-     * security warning is not effected by resizing of the window.
-     * <p>
-     * Note that the security warning management code guarantees that:
-     * <ul>
-     * <li>The security warning cannot be located farther than two pixels from
-     * the rectangular bounds of the window (see {@link Window#getBounds}), and
-     * <li>The security warning is always visible on the screen.
-     * </ul>
-     * If either of the conditions is violated, the calculated position of the
-     * security warning is adjusted by the system to meet both these
-     * conditions.
-     * <p>
-     * The default position of the security warning is in the upper-right
-     * corner of the window, two pixels to the right from the right edge. This
-     * corresponds to the following arguments passed to this method:
-     * <ul>
-     * <li>{@code alignmentX = Component.RIGHT_ALIGNMENT}
-     * <li>{@code alignmentY = Component.TOP_ALIGNMENT}
-     * <li>{@code point = (2, 0)}
-     * </ul>
-     *
-     * @param window the window to set the position of the security warning for
-     * @param alignmentX the horizontal origin of the coordinate system
-     * @param alignmentY the vertical origin of the coordinate system
-     * @param point the position of the security warning in the specified
-     * coordinate system
-     *
-     * @throws NullPointerException if the window argument is null
-     * @throws NullPointerException if the point argument is null
-     * @throws IllegalArgumentException if the window is trusted (i.e.
-     * the {@code getWarningString()} returns null
-     * @throws IllegalArgumentException if the alignmentX or alignmentY
-     * arguments are not within the range [0.0f ... 1.0f]
-     */
-    public static void setPosition(Window window, Point2D point,
-            float alignmentX, float alignmentY)
-    {
-        if (window == null) {
-            throw new NullPointerException(
-                    "The window argument should not be null.");
-        }
-        if (window.getWarningString() == null) {
-            throw new IllegalArgumentException(
-                    "The window must have a non-null warning string.");
-        }
-        if (point == null) {
-            throw new NullPointerException(
-                    "The point argument must not be null");
-        }
-        if (alignmentX < 0.0f || alignmentX > 1.0f) {
-            throw new IllegalArgumentException(
-                    "alignmentX must be in the range [0.0f ... 1.0f].");
-        }
-        if (alignmentY < 0.0f || alignmentY > 1.0f) {
-            throw new IllegalArgumentException(
-                    "alignmentY must be in the range [0.0f ... 1.0f].");
-        }
-
-        AWTAccessor.getWindowAccessor().setSecurityWarningPosition(window,
-                point, alignmentX, alignmentY);
-    }
-}
-
--- a/src/java.desktop/share/classes/com/sun/media/sound/DirectAudioDevice.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/java.desktop/share/classes/com/sun/media/sound/DirectAudioDevice.java	Mon Oct 01 09:56:45 2018 +0100
@@ -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.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -547,14 +547,15 @@
                 getEventDispatcher().addLineMonitor(this);
             }
 
-            doIO = true;
-
-            // need to set Active and Started
-            // note: the current API always requires that
-            //       Started and Active are set at the same time...
-            if (isSource && stoppedWritten) {
-                setStarted(true);
-                setActive(true);
+            synchronized(lock) {
+                doIO = true;
+                // need to set Active and Started
+                // note: the current API always requires that
+                //       Started and Active are set at the same time...
+                if (isSource && stoppedWritten) {
+                    setStarted(true);
+                    setActive(true);
+                }
             }
 
             if (Printer.trace) Printer.trace("<< DirectDL: implStart() succeeded");
@@ -582,10 +583,10 @@
                 // read/write thread, that's why isStartedRunning()
                 // cannot be used
                 doIO = false;
+                setActive(false);
+                setStarted(false);
                 lock.notifyAll();
             }
-            setActive(false);
-            setStarted(false);
             stoppedWritten = false;
 
             if (Printer.trace) Printer.trace(" << DirectDL: implStop() succeeded");
@@ -731,12 +732,14 @@
             if ((long)off + (long)len > (long)b.length) {
                 throw new ArrayIndexOutOfBoundsException(b.length);
             }
-
-            if (!isActive() && doIO) {
-                // this is not exactly correct... would be nicer
-                // if the native sub system sent a callback when IO really starts
-                setActive(true);
-                setStarted(true);
+            synchronized(lock) {
+                if (!isActive() && doIO) {
+                    // this is not exactly correct... would be nicer
+                    // if the native sub system sent a callback when IO really
+                    // starts
+                    setActive(true);
+                    setStarted(true);
+                }
             }
             int written = 0;
             while (!flushing) {
@@ -957,11 +960,14 @@
             if ((long)off + (long)len > (long)b.length) {
                 throw new ArrayIndexOutOfBoundsException(b.length);
             }
-            if (!isActive() && doIO) {
-                // this is not exactly correct... would be nicer
-                // if the native sub system sent a callback when IO really starts
-                setActive(true);
-                setStarted(true);
+            synchronized(lock) {
+                if (!isActive() && doIO) {
+                    // this is not exactly correct... would be nicer
+                    // if the native sub system sent a callback when IO really
+                    // starts
+                    setActive(true);
+                    setStarted(true);
+                }
             }
             int read = 0;
             while (doIO && !flushing) {
--- a/src/java.desktop/share/classes/java/awt/GraphicsEnvironment.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/java.desktop/share/classes/java/awt/GraphicsEnvironment.java	Mon Oct 01 09:56:45 2018 +0100
@@ -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
@@ -169,18 +169,9 @@
                 String nm = System.getProperty("java.awt.headless");
 
                 if (nm == null) {
-                    /* No need to ask for DISPLAY when run in a browser */
-                    if (System.getProperty("javaplugin.version") != null) {
-                        headless = defaultHeadless = Boolean.FALSE;
-                    } else {
-                        String osName = System.getProperty("os.name");
-                        if (osName.contains("OS X") && "sun.awt.HToolkit".equals(
-                                System.getProperty("awt.toolkit")))
-                        {
-                            headless = defaultHeadless = Boolean.TRUE;
-                        } else {
-                            final String display = System.getenv("DISPLAY");
-                            headless = defaultHeadless =
+                    final String osName = System.getProperty("os.name");
+                    final String display = System.getenv("DISPLAY");
+                    headless = defaultHeadless =
                                 ("Linux".equals(osName) ||
                                  "SunOS".equals(osName) ||
                                  "FreeBSD".equals(osName) ||
@@ -188,8 +179,6 @@
                                  "OpenBSD".equals(osName) ||
                                  "AIX".equals(osName)) &&
                                  (display == null || display.trim().isEmpty());
-                        }
-                    }
                 } else {
                     headless = Boolean.valueOf(nm);
                 }
--- a/src/java.desktop/share/classes/java/awt/Window.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/java.desktop/share/classes/java/awt/Window.java	Mon Oct 01 09:56:45 2018 +0100
@@ -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
@@ -394,16 +394,6 @@
     private transient volatile int securityWarningWidth = 0;
     private transient volatile int securityWarningHeight = 0;
 
-    /**
-     * These fields represent the desired location for the security
-     * warning if this window is untrusted.
-     * See com.sun.awt.SecurityWarning for more details.
-     */
-    private transient double securityWarningPointX = 2.0;
-    private transient double securityWarningPointY = 0.0;
-    private transient float securityWarningAlignmentX = RIGHT_ALIGNMENT;
-    private transient float securityWarningAlignmentY = TOP_ALIGNMENT;
-
     static {
         /* ensure that the necessary native libraries are loaded */
         Toolkit.loadLibraries();
@@ -3127,10 +3117,6 @@
 
          this.securityWarningWidth = 0;
          this.securityWarningHeight = 0;
-         this.securityWarningPointX = 2.0;
-         this.securityWarningPointY = 0.0;
-         this.securityWarningAlignmentX = RIGHT_ALIGNMENT;
-         this.securityWarningAlignmentY = TOP_ALIGNMENT;
 
          deserializeResources(s);
     }
@@ -4031,9 +4017,9 @@
     private Point2D calculateSecurityWarningPosition(double x, double y,
             double w, double h)
     {
-        // The position according to the spec of SecurityWarning.setPosition()
-        double wx = x + w * securityWarningAlignmentX + securityWarningPointX;
-        double wy = y + h * securityWarningAlignmentY + securityWarningPointY;
+         // The desired location for the security warning
+        double wx = x + w * RIGHT_ALIGNMENT + 2.0;
+        double wy = y + h * TOP_ALIGNMENT + 0.0;
 
         // First, make sure the warning is not too far from the window bounds
         wx = Window.limit(wx,
@@ -4068,33 +4054,12 @@
                 window.updateWindow();
             }
 
-            public Dimension getSecurityWarningSize(Window window) {
-                return new Dimension(window.securityWarningWidth,
-                        window.securityWarningHeight);
-            }
-
             public void setSecurityWarningSize(Window window, int width, int height)
             {
                 window.securityWarningWidth = width;
                 window.securityWarningHeight = height;
             }
 
-            public void setSecurityWarningPosition(Window window,
-                    Point2D point, float alignmentX, float alignmentY)
-            {
-                window.securityWarningPointX = point.getX();
-                window.securityWarningPointY = point.getY();
-                window.securityWarningAlignmentX = alignmentX;
-                window.securityWarningAlignmentY = alignmentY;
-
-                synchronized (window.getTreeLock()) {
-                    WindowPeer peer = (WindowPeer) window.peer;
-                    if (peer != null) {
-                        peer.repositionSecurityWarning();
-                    }
-                }
-            }
-
             public Point2D calculateSecurityWarningPosition(Window window,
                     double x, double y, double w, double h)
             {
--- a/src/java.desktop/share/classes/javax/swing/RepaintManager.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/java.desktop/share/classes/javax/swing/RepaintManager.java	Mon Oct 01 09:56:45 2018 +0100
@@ -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
@@ -1814,12 +1814,6 @@
      */
     private static final class DisplayChangedHandler implements
                                              DisplayChangedListener {
-        // Empty non private constructor was added because access to this
-        // class shouldn't be generated by the compiler using synthetic
-        // accessor method
-        DisplayChangedHandler() {
-        }
-
         public void displayChanged() {
             scheduleDisplayChanges();
         }
--- a/src/java.desktop/share/classes/javax/swing/border/TitledBorder.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/java.desktop/share/classes/javax/swing/border/TitledBorder.java	Mon Oct 01 09:56:45 2018 +0100
@@ -42,6 +42,8 @@
 import javax.swing.UIManager;
 import javax.swing.plaf.basic.BasicHTML;
 
+import jdk.internal.ref.CleanerFactory;
+
 /**
  * A class which implements an arbitrary border
  * with the addition of a String title in a
@@ -759,22 +761,19 @@
 
     private void installPropertyChangeListeners() {
         final WeakReference<TitledBorder> weakReference = new WeakReference<TitledBorder>(this);
-        final PropertyChangeListener listener = new PropertyChangeListener() {
-            @Override
-            public void propertyChange(PropertyChangeEvent evt) {
-                if (weakReference.get() == null) {
-                    UIManager.removePropertyChangeListener(this);
-                    UIManager.getDefaults().removePropertyChangeListener(this);
-                } else {
-                    String prop = evt.getPropertyName();
-                    if ("lookAndFeel".equals(prop) || "LabelUI".equals(prop)) {
-                        label.updateUI();
-                    }
-                }
+        final PropertyChangeListener listener = evt -> {
+            TitledBorder tb = weakReference.get();
+            String prop = evt.getPropertyName();
+            if (tb != null && ("lookAndFeel".equals(prop) || "LabelUI".equals(prop))) {
+                tb.label.updateUI();
             }
         };
 
         UIManager.addPropertyChangeListener(listener);
         UIManager.getDefaults().addPropertyChangeListener(listener);
+        CleanerFactory.cleaner().register(this, () -> {
+            UIManager.removePropertyChangeListener(listener);
+            UIManager.getDefaults().removePropertyChangeListener(listener);
+        });
     }
 }
--- a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicProgressBarUI.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicProgressBarUI.java	Mon Oct 01 09:56:45 2018 +0100
@@ -874,7 +874,7 @@
                                                       progressString);
 
         if (progressBar.getOrientation() == JProgressBar.HORIZONTAL) {
-            return new Point(x + Math.round(width/2 - stringWidth/2),
+            return new Point(x + (int)Math.round(width/2.0 - stringWidth/2.0),
                              y + ((height +
                                  fontSizer.getAscent() -
                                  fontSizer.getLeading() -
@@ -882,7 +882,7 @@
         } else { // VERTICAL
             return new Point(x + ((width - fontSizer.getAscent() +
                     fontSizer.getLeading() + fontSizer.getDescent()) / 2),
-                    y + Math.round(height/2 - stringWidth/2));
+                    y + (int)Math.round(height/2.0 - stringWidth/2.0));
         }
     }
 
--- a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicTableUI.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicTableUI.java	Mon Oct 01 09:56:45 2018 +0100
@@ -1872,7 +1872,12 @@
             // and if there is any selected rows
             if (rMax != (table.getRowCount() - 1) &&
                     (table.getSelectedRow() == -1)) {
-                rMax = rMax - 1;
+                // Do not decrement rMax if rMax becomes
+                // less than or equal to rMin
+                // else cells will not be painted
+                if (rMax - rMin > 1) {
+                    rMax = rMax - 1;
+                }
             }
         }
 
--- a/src/java.desktop/share/classes/javax/swing/text/html/StyleSheet.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/java.desktop/share/classes/javax/swing/text/html/StyleSheet.java	Mon Oct 01 09:56:45 2018 +0100
@@ -2339,18 +2339,26 @@
          */
         void drawShape(Graphics g, CSS.Value type, int ax, int ay, int aw,
                        int ah, float align) {
-            // Align to bottom of shape.
-            int gap = isLeftToRight ? - (bulletgap + 8) : (aw + bulletgap);
+            final Object origAA = ((Graphics2D) g).getRenderingHint(
+                                             RenderingHints.KEY_ANTIALIASING);
+            ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING,
+                                            RenderingHints.VALUE_ANTIALIAS_ON);
+            int size = g.getFont().getSize();
+
+            // Position shape to the middle of the html text.
+            int gap = isLeftToRight ? - (bulletgap + size/3) : (aw + bulletgap);
             int x = ax + gap;
-            int y = Math.max(ay, ay + (int)(align * ah) - 8);
+            int y = Math.max(ay, ay + (int)Math.ceil(ah/2));
 
             if (type == CSS.Value.SQUARE) {
-                g.drawRect(x, y, 8, 8);
+                g.drawRect(x, y, size/3, size/3);
             } else if (type == CSS.Value.CIRCLE) {
-                g.drawOval(x, y, 8, 8);
+                g.drawOval(x, y, size/3, size/3);
             } else {
-                g.fillOval(x, y, 8, 8);
+                g.fillOval(x, y, size/3, size/3);
             }
+            ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING,
+                                              origAA);
         }
 
         /**
--- a/src/java.desktop/share/classes/sun/applet/AppletClassLoader.java	Wed Sep 26 18:11:00 2018 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,854 +0,0 @@
-/*
- * 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
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.  Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package sun.applet;
-
-import java.io.BufferedInputStream;
-import java.io.EOFException;
-import java.io.File;
-import java.io.FilePermission;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.net.URLClassLoader;
-import java.net.URLConnection;
-import java.security.AccessControlContext;
-import java.security.AccessController;
-import java.security.CodeSource;
-import java.security.Permission;
-import java.security.PermissionCollection;
-import java.security.PrivilegedAction;
-import java.security.PrivilegedActionException;
-import java.security.PrivilegedExceptionAction;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.NoSuchElementException;
-
-import sun.awt.AppContext;
-import sun.awt.SunToolkit;
-import sun.net.www.ParseUtil;
-import sun.security.util.SecurityConstants;
-
-/**
- * This class defines the class loader for loading applet classes and
- * resources. It extends URLClassLoader to search the applet code base
- * for the class or resource after checking any loaded JAR files.
- */
-public class AppletClassLoader extends URLClassLoader {
-    private URL base;   /* applet code base URL */
-    private CodeSource codesource; /* codesource for the base URL */
-    private AccessControlContext acc;
-    private boolean exceptionStatus = false;
-
-    private final Object threadGroupSynchronizer = new Object();
-    private final Object grabReleaseSynchronizer = new Object();
-
-    private boolean codebaseLookup = true;
-    private volatile boolean allowRecursiveDirectoryRead = true;
-
-    /*
-     * Creates a new AppletClassLoader for the specified base URL.
-     */
-    protected AppletClassLoader(URL base) {
-        super(new URL[0]);
-        this.base = base;
-        this.codesource =
-            new CodeSource(base, (java.security.cert.Certificate[]) null);
-        acc = AccessController.getContext();
-    }
-
-    public void disableRecursiveDirectoryRead() {
-        allowRecursiveDirectoryRead = false;
-    }
-
-
-    /**
-     * Set the codebase lookup flag.
-     */
-    void setCodebaseLookup(boolean codebaseLookup)  {
-        this.codebaseLookup = codebaseLookup;
-    }
-
-    /*
-     * Returns the applet code base URL.
-     */
-    URL getBaseURL() {
-        return base;
-    }
-
-    /*
-     * Returns the URLs used for loading classes and resources.
-     */
-    public URL[] getURLs() {
-        URL[] jars = super.getURLs();
-        URL[] urls = new URL[jars.length + 1];
-        System.arraycopy(jars, 0, urls, 0, jars.length);
-        urls[urls.length - 1] = base;
-        return urls;
-    }
-
-    /*
-     * Adds the specified JAR file to the search path of loaded JAR files.
-     * Changed modifier to protected in order to be able to overwrite addJar()
-     * in PluginClassLoader.java
-     */
-    protected void addJar(String name) throws IOException {
-        URL url;
-        try {
-            url = new URL(base, name);
-        } catch (MalformedURLException e) {
-            throw new IllegalArgumentException("name");
-        }
-        addURL(url);
-        // DEBUG
-        //URL[] urls = getURLs();
-        //for (int i = 0; i < urls.length; i++) {
-        //    System.out.println("url[" + i + "] = " + urls[i]);
-        //}
-    }
-
-    /*
-     * Override loadClass so that class loading errors can be caught in
-     * order to print better error messages.
-     */
-    public synchronized Class<?> loadClass(String name, boolean resolve)
-        throws ClassNotFoundException
-    {
-        // First check if we have permission to access the package. This
-        // should go away once we've added support for exported packages.
-        int i = name.lastIndexOf('.');
-        if (i != -1) {
-            SecurityManager sm = System.getSecurityManager();
-            if (sm != null)
-                sm.checkPackageAccess(name.substring(0, i));
-        }
-        try {
-            return super.loadClass(name, resolve);
-        } catch (ClassNotFoundException e) {
-            throw e;
-        } catch (RuntimeException e) {
-            throw e;
-        } catch (Error e) {
-            throw e;
-        }
-    }
-
-    /*
-     * Finds the applet class with the specified name. First searches
-     * loaded JAR files then the applet code base for the class.
-     */
-    protected Class<?> findClass(String name) throws ClassNotFoundException {
-
-        int index = name.indexOf(';');
-        String cookie = "";
-        if(index != -1) {
-                cookie = name.substring(index, name.length());
-                name = name.substring(0, index);
-        }
-
-        // check loaded JAR files
-        try {
-            return super.findClass(name);
-        } catch (ClassNotFoundException e) {
-        }
-
-        // Otherwise, try loading the class from the code base URL
-
-        // 4668479: Option to turn off codebase lookup in AppletClassLoader
-        // during resource requests. [stanley.ho]
-        if (codebaseLookup == false)
-            throw new ClassNotFoundException(name);
-
-//      final String path = name.replace('.', '/').concat(".class").concat(cookie);
-        String encodedName = ParseUtil.encodePath(name.replace('.', '/'), false);
-        final String path = (new StringBuffer(encodedName)).append(".class").append(cookie).toString();
-        try {
-            byte[] b = AccessController.doPrivileged(
-                               new PrivilegedExceptionAction<byte[]>() {
-                public byte[] run() throws IOException {
-                   try {
-                        URL finalURL = new URL(base, path);
-
-                        // Make sure the codebase won't be modified
-                        if (base.getProtocol().equals(finalURL.getProtocol()) &&
-                            base.getHost().equals(finalURL.getHost()) &&
-                            base.getPort() == finalURL.getPort()) {
-                            return getBytes(finalURL);
-                        }
-                        else {
-                            return null;
-                        }
-                    } catch (Exception e) {
-                        return null;
-                    }
-                }
-            }, acc);
-
-            if (b != null) {
-                return defineClass(name, b, 0, b.length, codesource);
-            } else {
-                throw new ClassNotFoundException(name);
-            }
-        } catch (PrivilegedActionException e) {
-            throw new ClassNotFoundException(name, e.getException());
-        }
-    }
-
-    /**
-     * Returns the permissions for the given codesource object.
-     * The implementation of this method first calls super.getPermissions,
-     * to get the permissions
-     * granted by the super class, and then adds additional permissions
-     * based on the URL of the codesource.
-     * <p>
-     * If the protocol is "file"
-     * and the path specifies a file, permission is granted to read all files
-     * and (recursively) all files and subdirectories contained in
-     * that directory. This is so applets with a codebase of
-     * file:/blah/some.jar can read in file:/blah/, which is needed to
-     * be backward compatible. We also add permission to connect back to
-     * the "localhost".
-     *
-     * @param codesource the codesource
-     * @throws NullPointerException if {@code codesource} is {@code null}.
-     * @return the permissions granted to the codesource
-     */
-    protected PermissionCollection getPermissions(CodeSource codesource)
-    {
-        final PermissionCollection perms = super.getPermissions(codesource);
-
-        URL url = codesource.getLocation();
-
-        String path = null;
-        Permission p;
-
-        try {
-            p = url.openConnection().getPermission();
-        } catch (java.io.IOException ioe) {
-            p = null;
-        }
-
-        if (p instanceof FilePermission) {
-            path = p.getName();
-        } else if ((p == null) && (url.getProtocol().equals("file"))) {
-            path = url.getFile().replace('/', File.separatorChar);
-            path = ParseUtil.decode(path);
-        }
-
-        if (path != null) {
-            final String rawPath = path;
-            if (!path.endsWith(File.separator)) {
-                int endIndex = path.lastIndexOf(File.separatorChar);
-                if (endIndex != -1) {
-                        path = path.substring(0, endIndex + 1) + "-";
-                        perms.add(new FilePermission(path,
-                            SecurityConstants.FILE_READ_ACTION));
-                }
-            }
-            final File f = new File(rawPath);
-            final boolean isDirectory = f.isDirectory();
-            // grant codebase recursive read permission
-            // this should only be granted to non-UNC file URL codebase and
-            // the codesource path must either be a directory, or a file
-            // that ends with .jar or .zip
-            if (allowRecursiveDirectoryRead && (isDirectory ||
-                    rawPath.toLowerCase().endsWith(".jar") ||
-                    rawPath.toLowerCase().endsWith(".zip"))) {
-
-            Permission bperm;
-                try {
-                    bperm = base.openConnection().getPermission();
-                } catch (java.io.IOException ioe) {
-                    bperm = null;
-                }
-                if (bperm instanceof FilePermission) {
-                    String bpath = bperm.getName();
-                    if (bpath.endsWith(File.separator)) {
-                        bpath += "-";
-                    }
-                    perms.add(new FilePermission(bpath,
-                        SecurityConstants.FILE_READ_ACTION));
-                } else if ((bperm == null) && (base.getProtocol().equals("file"))) {
-                    String bpath = base.getFile().replace('/', File.separatorChar);
-                    bpath = ParseUtil.decode(bpath);
-                    if (bpath.endsWith(File.separator)) {
-                        bpath += "-";
-                    }
-                    perms.add(new FilePermission(bpath, SecurityConstants.FILE_READ_ACTION));
-                }
-
-            }
-        }
-        return perms;
-    }
-
-    /*
-     * Returns the contents of the specified URL as an array of bytes.
-     */
-    private static byte[] getBytes(URL url) throws IOException {
-        URLConnection uc = url.openConnection();
-        if (uc instanceof java.net.HttpURLConnection) {
-            java.net.HttpURLConnection huc = (java.net.HttpURLConnection) uc;
-            int code = huc.getResponseCode();
-            if (code >= java.net.HttpURLConnection.HTTP_BAD_REQUEST) {
-                throw new IOException("open HTTP connection failed.");
-            }
-        }
-        int len = uc.getContentLength();
-
-        // Fixed #4507227: Slow performance to load
-        // class and resources. [stanleyh]
-        //
-        // Use buffered input stream [stanleyh]
-        InputStream in = new BufferedInputStream(uc.getInputStream());
-
-        byte[] b;
-        try {
-            b = in.readAllBytes();
-            if (len != -1 && b.length != len)
-                throw new EOFException("Expected:" + len + ", read:" + b.length);
-        } finally {
-            in.close();
-        }
-        return b;
-    }
-
-    // Object for synchronization around getResourceAsStream()
-    private Object syncResourceAsStream = new Object();
-    private Object syncResourceAsStreamFromJar = new Object();
-
-    // Flag to indicate getResourceAsStream() is in call
-    private boolean resourceAsStreamInCall = false;
-    private boolean resourceAsStreamFromJarInCall = false;
-
-    /**
-     * Returns an input stream for reading the specified resource.
-     *
-     * The search order is described in the documentation for {@link
-     * #getResource(String)}.<p>
-     *
-     * @param  name the resource name
-     * @return an input stream for reading the resource, or {@code null}
-     *         if the resource could not be found
-     * @since  1.1
-     */
-    public InputStream getResourceAsStream(String name)
-    {
-
-        if (name == null) {
-            throw new NullPointerException("name");
-        }
-
-        try
-        {
-            InputStream is = null;
-
-            // Fixed #4507227: Slow performance to load
-            // class and resources. [stanleyh]
-            //
-            // The following is used to avoid calling
-            // AppletClassLoader.findResource() in
-            // super.getResourceAsStream(). Otherwise,
-            // unnecessary connection will be made.
-            //
-            synchronized(syncResourceAsStream)
-            {
-                resourceAsStreamInCall = true;
-
-                // Call super class
-                is = super.getResourceAsStream(name);
-
-                resourceAsStreamInCall = false;
-            }
-
-            // 4668479: Option to turn off codebase lookup in AppletClassLoader
-            // during resource requests. [stanley.ho]
-            if (codebaseLookup == true && is == null)
-            {
-                // If resource cannot be obtained,
-                // try to download it from codebase
-                URL url = new URL(base, ParseUtil.encodePath(name, false));
-                is = url.openStream();
-            }
-
-            return is;
-        }
-        catch (Exception e)
-        {
-            return null;
-        }
-    }
-
-
-    /**
-     * Returns an input stream for reading the specified resource from the
-     * the loaded jar files.
-     *
-     * The search order is described in the documentation for {@link
-     * #getResource(String)}.<p>
-     *
-     * @param  name the resource name
-     * @return an input stream for reading the resource, or {@code null}
-     *         if the resource could not be found
-     * @since  1.1
-     */
-    public InputStream getResourceAsStreamFromJar(String name) {
-
-        if (name == null) {
-            throw new NullPointerException("name");
-        }
-
-        try {
-            InputStream is = null;
-            synchronized(syncResourceAsStreamFromJar) {
-                resourceAsStreamFromJarInCall = true;
-                // Call super class
-                is = super.getResourceAsStream(name);
-                resourceAsStreamFromJarInCall = false;
-            }
-
-            return is;
-        } catch (Exception e) {
-            return null;
-        }
-    }
-
-
-    /*
-     * Finds the applet resource with the specified name. First checks
-     * loaded JAR files then the applet code base for the resource.
-     */
-    public URL findResource(String name) {
-        // check loaded JAR files
-        URL url = super.findResource(name);
-
-        // 6215746:  Disable META-INF/* lookup from codebase in
-        // applet/plugin classloader. [stanley.ho]
-        if (name.startsWith("META-INF/"))
-            return url;
-
-        // 4668479: Option to turn off codebase lookup in AppletClassLoader
-        // during resource requests. [stanley.ho]
-        if (codebaseLookup == false)
-            return url;
-
-        if (url == null)
-        {
-            //#4805170, if it is a call from Applet.getImage()
-            //we should check for the image only in the archives
-            boolean insideGetResourceAsStreamFromJar = false;
-                synchronized(syncResourceAsStreamFromJar) {
-                insideGetResourceAsStreamFromJar = resourceAsStreamFromJarInCall;
-            }
-
-            if (insideGetResourceAsStreamFromJar) {
-                return null;
-            }
-
-            // Fixed #4507227: Slow performance to load
-            // class and resources. [stanleyh]
-            //
-            // Check if getResourceAsStream is called.
-            //
-            boolean insideGetResourceAsStream = false;
-
-            synchronized(syncResourceAsStream)
-            {
-                insideGetResourceAsStream = resourceAsStreamInCall;
-            }
-
-            // If getResourceAsStream is called, don't
-            // trigger the following code. Otherwise,
-            // unnecessary connection will be made.
-            //
-            if (insideGetResourceAsStream == false)
-            {
-                // otherwise, try the code base
-                try {
-                    url = new URL(base, ParseUtil.encodePath(name, false));
-                    // check if resource exists
-                    if(!resourceExists(url))
-                        url = null;
-                } catch (Exception e) {
-                    // all exceptions, including security exceptions, are caught
-                    url = null;
-                }
-            }
-        }
-        return url;
-    }
-
-
-    private boolean resourceExists(URL url) {
-        // Check if the resource exists.
-        // It almost works to just try to do an openConnection() but
-        // HttpURLConnection will return true on HTTP_BAD_REQUEST
-        // when the requested name ends in ".html", ".htm", and ".txt"
-        // and we want to be able to handle these
-        //
-        // Also, cannot just open a connection for things like FileURLConnection,
-        // because they succeed when connecting to a nonexistent file.
-        // So, in those cases we open and close an input stream.
-        boolean ok = true;
-        try {
-            URLConnection conn = url.openConnection();
-            if (conn instanceof java.net.HttpURLConnection) {
-                java.net.HttpURLConnection hconn =
-                    (java.net.HttpURLConnection) conn;
-
-                // To reduce overhead, using http HEAD method instead of GET method
-                hconn.setRequestMethod("HEAD");
-
-                int code = hconn.getResponseCode();
-                if (code == java.net.HttpURLConnection.HTTP_OK) {
-                    return true;
-                }
-                if (code >= java.net.HttpURLConnection.HTTP_BAD_REQUEST) {
-                    return false;
-                }
-            } else {
-                /**
-                 * Fix for #4182052 - stanleyh
-                 *
-                 * The same connection should be reused to avoid multiple
-                 * HTTP connections
-                 */
-
-                // our best guess for the other cases
-                InputStream is = conn.getInputStream();
-                is.close();
-            }
-        } catch (Exception ex) {
-            ok = false;
-        }
-        return ok;
-    }
-
-    /*
-     * Returns an enumeration of all the applet resources with the specified
-     * name. First checks loaded JAR files then the applet code base for all
-     * available resources.
-     */
-    @Override
-    public Enumeration<URL> findResources(String name) throws IOException {
-
-        final Enumeration<URL> e = super.findResources(name);
-
-        // 6215746:  Disable META-INF/* lookup from codebase in
-        // applet/plugin classloader. [stanley.ho]
-        if (name.startsWith("META-INF/"))
-            return e;
-
-        // 4668479: Option to turn off codebase lookup in AppletClassLoader
-        // during resource requests. [stanley.ho]
-        if (codebaseLookup == false)
-            return e;
-
-        URL u = new URL(base, ParseUtil.encodePath(name, false));
-        if (!resourceExists(u)) {
-            u = null;
-        }
-
-        final URL url = u;
-        return new Enumeration<URL>() {
-            private boolean done;
-            public URL nextElement() {
-                if (!done) {
-                    if (e.hasMoreElements()) {
-                        return e.nextElement();
-                    }
-                    done = true;
-                    if (url != null) {
-                        return url;
-                    }
-                }
-                throw new NoSuchElementException();
-            }
-            public boolean hasMoreElements() {
-                return !done && (e.hasMoreElements() || url != null);
-            }
-        };
-    }
-
-    /*
-     * Load and resolve the file specified by the applet tag CODE
-     * attribute. The argument can either be the relative path
-     * of the class file itself or just the name of the class.
-     */
-    Class<?> loadCode(String name) throws ClassNotFoundException {
-        // first convert any '/' or native file separator to .
-        name = name.replace('/', '.');
-        name = name.replace(File.separatorChar, '.');
-
-        // deal with URL rewriting
-        String cookie = null;
-        int index = name.indexOf(';');
-        if(index != -1) {
-                cookie = name.substring(index, name.length());
-                name = name.substring(0, index);
-        }
-
-        // save that name for later
-        String fullName = name;
-        // then strip off any suffixes
-        if (name.endsWith(".class") || name.endsWith(".java")) {
-            name = name.substring(0, name.lastIndexOf('.'));
-        }
-        try {
-                if(cookie != null)
-                        name = (new StringBuffer(name)).append(cookie).toString();
-            return loadClass(name);
-        } catch (ClassNotFoundException e) {
-        }
-        // then if it didn't end with .java or .class, or in the
-        // really pathological case of a class named class or java
-        if(cookie != null)
-                fullName = (new StringBuffer(fullName)).append(cookie).toString();
-
-        return loadClass(fullName);
-    }
-
-    /*
-     * The threadgroup that the applets loaded by this classloader live
-     * in. In the sun.* implementation of applets, the security manager's
-     * (AppletSecurity) getThreadGroup returns the thread group of the
-     * first applet on the stack, which is the applet's thread group.
-     */
-    private AppletThreadGroup threadGroup;
-    private AppContext appContext;
-
-    public ThreadGroup getThreadGroup() {
-      synchronized (threadGroupSynchronizer) {
-        if (threadGroup == null || threadGroup.isDestroyed()) {
-            AccessController.doPrivileged(new PrivilegedAction<Object>() {
-                public Object run() {
-                    threadGroup = new AppletThreadGroup(base + "-threadGroup");
-                    // threadGroup.setDaemon(true);
-                    // threadGroup is now destroyed by AppContext.dispose()
-
-                    // Create the new AppContext from within a Thread belonging
-                    // to the newly created ThreadGroup, and wait for the
-                    // creation to complete before returning from this method.
-                    AppContextCreator creatorThread = new AppContextCreator(threadGroup);
-
-                    // Since this thread will later be used to launch the
-                    // applet's AWT-event dispatch thread and we want the applet
-                    // code executing the AWT callbacks to use their own class
-                    // loader rather than the system class loader, explicitly
-                    // set the context class loader to the AppletClassLoader.
-                    creatorThread.setContextClassLoader(AppletClassLoader.this);
-
-                    creatorThread.start();
-                    try {
-                        synchronized(creatorThread.syncObject) {
-                            while (!creatorThread.created) {
-                                creatorThread.syncObject.wait();
-                            }
-                        }
-                    } catch (InterruptedException e) { }
-                    appContext = creatorThread.appContext;
-                    return null;
-                }
-            });
-        }
-        return threadGroup;
-      }
-    }
-
-    /*
-     * Get the AppContext, if any, corresponding to this AppletClassLoader.
-     */
-    public AppContext getAppContext()  {
-        return appContext;
-    }
-
-    int usageCount = 0;
-
-    /**
-     * Grab this AppletClassLoader and its ThreadGroup/AppContext, so they
-     * won't be destroyed.
-     */
-public     void grab() {
-        synchronized(grabReleaseSynchronizer) {
-            usageCount++;
-        }
-        getThreadGroup(); // Make sure ThreadGroup/AppContext exist
-    }
-
-    protected void setExceptionStatus()
-    {
-        exceptionStatus = true;
-    }
-
-    public boolean getExceptionStatus()
-    {
-        return exceptionStatus;
-    }
-
-    /**
-     * Release this AppletClassLoader and its ThreadGroup/AppContext.
-     * If nothing else has grabbed this AppletClassLoader, its ThreadGroup
-     * and AppContext will be destroyed.
-     *
-     * Because this method may destroy the AppletClassLoader's ThreadGroup,
-     * this method should NOT be called from within the AppletClassLoader's
-     * ThreadGroup.
-     *
-     * Changed modifier to protected in order to be able to overwrite this
-     * function in PluginClassLoader.java
-     */
-    protected void release() {
-
-        AppContext tempAppContext = null;
-
-        synchronized(grabReleaseSynchronizer) {
-            if (usageCount > 1)  {
-                --usageCount;
-            } else {
-                synchronized(threadGroupSynchronizer) {
-                    tempAppContext = resetAppContext();
-                }
-            }
-        }
-
-        // Dispose appContext outside any sync block to
-        // prevent potential deadlock.
-        if (tempAppContext != null)  {
-            try {
-                tempAppContext.dispose(); // nuke the world!
-            } catch (IllegalThreadStateException e) { }
-        }
-    }
-
-    /*
-     * reset classloader's AppContext and ThreadGroup
-     * This method is for subclass PluginClassLoader to
-     * reset superclass's AppContext and ThreadGroup but do
-     * not dispose the AppContext. PluginClassLoader does not
-     * use UsageCount to decide whether to dispose AppContext
-     *
-     * @return previous AppContext
-     */
-    protected AppContext resetAppContext() {
-        AppContext tempAppContext = null;
-
-        synchronized(threadGroupSynchronizer) {
-            // Store app context in temp variable
-            tempAppContext = appContext;
-            usageCount = 0;
-            appContext = null;
-            threadGroup = null;
-        }
-        return tempAppContext;
-    }
-
-
-    // Hash map to store applet compatibility info
-    private HashMap<String, Boolean> jdk11AppletInfo = new HashMap<>();
-    private HashMap<String, Boolean> jdk12AppletInfo = new HashMap<>();
-
-    /**
-     * Set applet target level as JDK 1.1.
-     *
-     * @param clazz Applet class.
-     * @param bool true if JDK is targeted for JDK 1.1;
-     *             false otherwise.
-     */
-    void setJDK11Target(Class<?> clazz, boolean bool)
-    {
-         jdk11AppletInfo.put(clazz.toString(), Boolean.valueOf(bool));
-    }
-
-    /**
-     * Set applet target level as JDK 1.2.
-     *
-     * @param clazz Applet class.
-     * @param bool true if JDK is targeted for JDK 1.2;
-     *             false otherwise.
-     */
-    void setJDK12Target(Class<?> clazz, boolean bool)
-    {
-        jdk12AppletInfo.put(clazz.toString(), Boolean.valueOf(bool));
-    }
-
-    /**
-     * Determine if applet is targeted for JDK 1.1.
-     *
-     * @param  clazz Applet class.
-     * @return TRUE if applet is targeted for JDK 1.1;
-     *         FALSE if applet is not;
-     *         null if applet is unknown.
-     */
-    Boolean isJDK11Target(Class<?> clazz)
-    {
-        return jdk11AppletInfo.get(clazz.toString());
-    }
-
-    /**
-     * Determine if applet is targeted for JDK 1.2.
-     *
-     * @param  clazz Applet class.
-     * @return TRUE if applet is targeted for JDK 1.2;
-     *         FALSE if applet is not;
-     *         null if applet is unknown.
-     */
-    Boolean isJDK12Target(Class<?> clazz)
-    {
-        return jdk12AppletInfo.get(clazz.toString());
-    }
-}
-
-/*
- * The AppContextCreator class is used to create an AppContext from within
- * a Thread belonging to the new AppContext's ThreadGroup.  To wait for
- * this operation to complete before continuing, wait for the notifyAll()
- * operation on the syncObject to occur.
- */
-class AppContextCreator extends Thread {
-    Object syncObject = new Object();
-    AppContext appContext = null;
-    volatile boolean created = false;
-
-    /**
-     * Must call the 5-args super-class constructor to erase locals.
-     */
-    private AppContextCreator() {
-        throw new UnsupportedOperationException("Must erase locals");
-    }
-
-    AppContextCreator(ThreadGroup group)  {
-        super(group, null, "AppContextCreator", 0, false);
-    }
-
-    public void run()  {
-        appContext = SunToolkit.createNewAppContext();
-        created = true;
-        synchronized(syncObject) {
-            syncObject.notifyAll();
-        }
-    } // run()
-
-} // class AppContextCreator
--- a/src/java.desktop/share/classes/sun/applet/AppletSecurity.java	Wed Sep 26 18:11:00 2018 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,421 +0,0 @@
-/*
- * 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
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.  Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package sun.applet;
-
-import java.io.File;
-import java.io.FilePermission;
-import java.io.IOException;
-import java.io.FileDescriptor;
-import java.net.URL;
-import java.net.URLClassLoader;
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-import java.net.SocketPermission;
-import java.util.Enumeration;
-import java.util.Iterator;
-import java.util.HashSet;
-import java.util.StringTokenizer;
-import java.security.*;
-import java.lang.reflect.*;
-import jdk.internal.misc.JavaNetURLClassLoaderAccess;
-import jdk.internal.misc.JavaSecurityAccess;
-import jdk.internal.misc.SharedSecrets;
-import sun.awt.AWTSecurityManager;
-import sun.awt.AppContext;
-import sun.awt.AWTPermissions;
-import sun.security.util.SecurityConstants;
-
-import static java.lang.StackWalker.*;
-import static java.lang.StackWalker.Option.*;
-
-
-/**
- * This class defines an applet security policy
- *
- */
-public
-class AppletSecurity extends AWTSecurityManager {
-    private static final JavaNetURLClassLoaderAccess JNUCLA
-            = SharedSecrets.getJavaNetURLClassLoaderAccess();
-    private static final JavaSecurityAccess JSA = SharedSecrets.getJavaSecurityAccess();
-
-    /**
-     * Construct and initialize.
-     */
-    public AppletSecurity() {
-        reset();
-    }
-
-    // Cache to store known restricted packages
-    private HashSet<String> restrictedPackages = new HashSet<>();
-
-    /**
-     * Reset from Properties
-     */
-    public void reset()
-    {
-        // Clear cache
-        restrictedPackages.clear();
-
-        AccessController.doPrivileged(new PrivilegedAction<Object>() {
-            public Object run()
-            {
-                // Enumerate system properties
-                Enumeration<?> e = System.getProperties().propertyNames();
-
-                while (e.hasMoreElements())
-                {
-                    String name = (String) e.nextElement();
-
-                    if (name != null && name.startsWith("package.restrict.access."))
-                    {
-                        String value = System.getProperty(name);
-
-                        if (value != null && value.equalsIgnoreCase("true"))
-                        {
-                            String pkg = name.substring(24);
-
-                            // Cache restricted packages
-                            restrictedPackages.add(pkg);
-                        }
-                    }
-                }
-                return null;
-            }
-        });
-    }
-
-    private static final StackWalker walker =
-        AccessController.doPrivileged(
-            (PrivilegedAction<StackWalker>) () ->
-                StackWalker.getInstance(RETAIN_CLASS_REFERENCE));
-    /**
-     * Returns the class loader of the most recently executing method from
-     * a class defined using a non-system class loader. A non-system
-     * class loader is defined as being a class loader that is not equal to
-     * the system class loader (as returned
-     * by {@link ClassLoader#getSystemClassLoader}) or one of its ancestors.
-     * <p>
-     * This method will return
-     * <code>null</code> in the following three cases:
-     * <ol>
-     *   <li>All methods on the execution stack are from classes
-     *   defined using the system class loader or one of its ancestors.
-     *
-     *   <li>All methods on the execution stack up to the first
-     *   "privileged" caller
-     *   (see {@link java.security.AccessController#doPrivileged})
-     *   are from classes
-     *   defined using the system class loader or one of its ancestors.
-     *
-     *   <li> A call to <code>checkPermission</code> with
-     *   <code>java.security.AllPermission</code> does not
-     *   result in a SecurityException.
-     * </ol>
-     *
-     * NOTE: This is an implementation of the SecurityManager.currentClassLoader
-     * method that uses StackWalker. SecurityManager.currentClassLoader
-     * has been removed from SE. This is a temporary workaround which is
-     * only needed while applets are still supported.
-     *
-     * @return  the class loader of the most recent occurrence on the stack
-     *          of a method from a class defined using a non-system class
-     *          loader.
-     */
-    private static ClassLoader currentClassLoader() {
-        StackFrame f =
-            walker.walk(s -> s.takeWhile(AppletSecurity::isNonPrivileged)
-                              .filter(AppletSecurity::isNonSystemFrame)
-                              .findFirst())
-                  .orElse(null);
-
-        SecurityManager sm = System.getSecurityManager();
-        if (f != null && sm != null) {
-            try {
-                sm.checkPermission(new AllPermission());
-            } catch (SecurityException se) {
-                return f.getDeclaringClass().getClassLoader();
-            }
-        }
-        return null;
-    }
-
-    /**
-     * Returns true if the StackFrame is not AccessController.doPrivileged.
-     */
-    private static boolean isNonPrivileged(StackFrame f) {
-        // possibly other doPrivileged variants
-        Class<?> c = f.getDeclaringClass();
-        return c == AccessController.class &&
-               f.getMethodName().equals("doPrivileged");
-    }
-
-    /**
-     * Returns true if the StackFrame is not from a class defined by the
-     * system class loader or one of its ancestors.
-     */
-    private static boolean isNonSystemFrame(StackFrame f) {
-        ClassLoader loader = ClassLoader.getSystemClassLoader();
-        ClassLoader ld = f.getDeclaringClass().getClassLoader();
-        if (ld == null || ld == loader) return false;
-
-        while ((loader = loader.getParent()) != null) {
-            if (ld == loader)
-                return false;
-        }
-        return true;
-    }
-
-    /**
-     * get the current (first) instance of an AppletClassLoader on the stack.
-     */
-    private AppletClassLoader currentAppletClassLoader()
-    {
-        // try currentClassLoader first
-        ClassLoader loader = currentClassLoader();
-
-        if ((loader == null) || (loader instanceof AppletClassLoader))
-            return (AppletClassLoader)loader;
-
-        // if that fails, get all the classes on the stack and check them.
-        Class<?>[] context = getClassContext();
-        for (int i = 0; i < context.length; i++) {
-            loader = context[i].getClassLoader();
-            if (loader instanceof AppletClassLoader)
-                return (AppletClassLoader)loader;
-        }
-
-        /*
-         * fix bug # 6433620 the logic here is : try to find URLClassLoader from
-         * class context, check its AccessControlContext to see if
-         * AppletClassLoader is in stack when it's created. for this kind of
-         * URLClassLoader, return the AppContext associated with the
-         * AppletClassLoader.
-         */
-        for (int i = 0; i < context.length; i++) {
-            final ClassLoader currentLoader = context[i].getClassLoader();
-
-            if (currentLoader instanceof URLClassLoader) {
-                URLClassLoader ld = (URLClassLoader)currentLoader;
-                loader = AccessController.doPrivileged(
-                    new PrivilegedAction<ClassLoader>() {
-                        public ClassLoader run() {
-
-                            AccessControlContext acc = null;
-                            ProtectionDomain[] pds = null;
-
-                            try {
-                                acc = JNUCLA.getAccessControlContext(ld);
-                                if (acc == null) {
-                                    return null;
-                                }
-
-                                pds = JSA.getProtectDomains(acc);
-                                if (pds == null) {
-                                    return null;
-                                }
-                            } catch (Exception e) {
-                                throw new UnsupportedOperationException(e);
-                            }
-
-                            for (int i=0; i<pds.length; i++) {
-                                ClassLoader cl = pds[i].getClassLoader();
-
-                                if (cl instanceof AppletClassLoader) {
-                                        return cl;
-                                }
-                            }
-
-                            return null;
-                        }
-                    });
-
-                if (loader != null) {
-                    return (AppletClassLoader) loader;
-                }
-            }
-        }
-
-        // if that fails, try the context class loader
-        loader = Thread.currentThread().getContextClassLoader();
-        if (loader instanceof AppletClassLoader)
-            return (AppletClassLoader)loader;
-
-        // no AppletClassLoaders on the stack
-        return (AppletClassLoader)null;
-    }
-
-    /**
-     * Returns true if this threadgroup is in the applet's own thread
-     * group. This will return false if there is no current class
-     * loader.
-     */
-    protected boolean inThreadGroup(ThreadGroup g) {
-        if (currentAppletClassLoader() == null)
-            return false;
-        else
-            return getThreadGroup().parentOf(g);
-    }
-
-    /**
-     * Returns true of the threadgroup of thread is in the applet's
-     * own threadgroup.
-     */
-    protected boolean inThreadGroup(Thread thread) {
-        return inThreadGroup(thread.getThreadGroup());
-    }
-
-    /**
-     * Applets are not allowed to manipulate threads outside
-     * applet thread groups. However a terminated thread no longer belongs
-     * to any group.
-     */
-    public void checkAccess(Thread t) {
-        /* When multiple applets is reloaded simultaneously, there will be
-         * multiple invocations to this method from plugin's SecurityManager.
-         * This method should not be synchronized to avoid deadlock when
-         * a page with multiple applets is reloaded
-         */
-        if ((t.getState() != Thread.State.TERMINATED) && !inThreadGroup(t)) {
-            checkPermission(SecurityConstants.MODIFY_THREAD_PERMISSION);
-        }
-    }
-
-    private boolean inThreadGroupCheck = false;
-
-    /**
-     * Applets are not allowed to manipulate thread groups outside
-     * applet thread groups.
-     */
-    public synchronized void checkAccess(ThreadGroup g) {
-        if (inThreadGroupCheck) {
-            // if we are in a recursive check, it is because
-            // inThreadGroup is calling appletLoader.getThreadGroup
-            // in that case, only do the super check, as appletLoader
-            // has a begin/endPrivileged
-            checkPermission(SecurityConstants.MODIFY_THREADGROUP_PERMISSION);
-        } else {
-            try {
-                inThreadGroupCheck = true;
-                if (!inThreadGroup(g)) {
-                    checkPermission(SecurityConstants.MODIFY_THREADGROUP_PERMISSION);
-                }
-            } finally {
-                inThreadGroupCheck = false;
-            }
-        }
-    }
-
-
-    /**
-     * Throws a {@code SecurityException} if the
-     * calling thread is not allowed to access the package specified by
-     * the argument.
-     * <p>
-     * This method is used by the {@code loadClass} method of class
-     * loaders.
-     * <p>
-     * The {@code checkPackageAccess} method for class
-     * {@code SecurityManager}  calls
-     * {@code checkPermission} with the
-     * {@code RuntimePermission("accessClassInPackage."+ pkgname)}
-     * permission.
-     *
-     * @param      pkgname   the package name.
-     * @exception  SecurityException  if the caller does not have
-     *             permission to access the specified package.
-     * @see        java.lang.ClassLoader#loadClass(java.lang.String, boolean)
-     */
-    public void checkPackageAccess(final String pkgname) {
-
-        // first see if the VM-wide policy allows access to this package
-        super.checkPackageAccess(pkgname);
-
-        // now check the list of restricted packages
-        for (Iterator<String> iter = restrictedPackages.iterator(); iter.hasNext();)
-        {
-            String pkg = iter.next();
-
-            // Prevent matching "sun" and "sunir" even if they
-            // starts with similar beginning characters
-            //
-            if (pkgname.equals(pkg) || pkgname.startsWith(pkg + "."))
-            {
-                checkPermission(new java.lang.RuntimePermission
-                            ("accessClassInPackage." + pkgname));
-            }
-        }
-    }
-
-    /**
-     * Returns the thread group of the applet. We consult the classloader
-     * if there is one.
-     */
-    public ThreadGroup getThreadGroup() {
-        /* If any applet code is on the execution stack, we return
-           that applet's ThreadGroup.  Otherwise, we use the default
-           behavior. */
-        AppletClassLoader appletLoader = currentAppletClassLoader();
-        ThreadGroup loaderGroup = (appletLoader == null) ? null
-                                          : appletLoader.getThreadGroup();
-        if (loaderGroup != null) {
-            return loaderGroup;
-        } else {
-            return super.getThreadGroup();
-        }
-    } // getThreadGroup()
-
-    /**
-      * Get the AppContext corresponding to the current context.
-      * The default implementation returns null, but this method
-      * may be overridden by various SecurityManagers
-      * (e.g. AppletSecurity) to index AppContext objects by the
-      * calling context.
-      *
-      * @return  the AppContext corresponding to the current context.
-      * @see     sun.awt.AppContext
-      * @see     java.lang.SecurityManager
-      * @since   1.2.1
-      */
-    public AppContext getAppContext() {
-        AppletClassLoader appletLoader = currentAppletClassLoader();
-
-        if (appletLoader == null) {
-            return null;
-        } else {
-            AppContext context =  appletLoader.getAppContext();
-
-            // context == null when some thread in applet thread group
-            // has not been destroyed in AppContext.dispose()
-            if (context == null) {
-                throw new SecurityException("Applet classloader has invalid AppContext");
-            }
-
-            return context;
-        }
-    }
-
-} // class AppletSecurity
--- a/src/java.desktop/share/classes/sun/applet/AppletThreadGroup.java	Wed Sep 26 18:11:00 2018 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,64 +0,0 @@
-/*
- * Copyright (c) 1995, 1997, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.  Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package sun.applet;
-
-/**
- * This class defines an applet thread group.
- *
- * @author      Arthur van Hoff
- */
-public class AppletThreadGroup extends ThreadGroup {
-
-    /**
-     * Constructs a new thread group for an applet.
-     * The parent of this new group is the thread
-     * group of the currently running thread.
-     *
-     * @param   name   the name of the new thread group.
-     */
-    public AppletThreadGroup(String name) {
-        this(Thread.currentThread().getThreadGroup(), name);
-    }
-
-    /**
-     * Creates a new thread group for an applet.
-     * The parent of this new group is the specified
-     * thread group.
-     *
-     * @param     parent   the parent thread group.
-     * @param     name     the name of the new thread group.
-     * @exception  NullPointerException  if the thread group argument is
-     *               {@code null}.
-     * @exception  SecurityException  if the current thread cannot create a
-     *               thread in the specified thread group.
-     * @see     java.lang.SecurityException
-     * @since   1.1.1
-     */
-    public AppletThreadGroup(ThreadGroup parent, String name) {
-        super(parent, name);
-        setMaxPriority(Thread.NORM_PRIORITY - 1);
-    }
-}
--- a/src/java.desktop/share/classes/sun/awt/AWTAccessor.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/java.desktop/share/classes/sun/awt/AWTAccessor.java	Mon Oct 01 09:56:45 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2008, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 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
@@ -295,20 +295,11 @@
          */
         void updateWindow(Window window);
 
-        /** Get the size of the security warning.
-         */
-        Dimension getSecurityWarningSize(Window w);
-
         /**
          * Set the size of the security warning.
          */
         void setSecurityWarningSize(Window w, int width, int height);
 
-        /** Set the position of the security warning.
-         */
-        void setSecurityWarningPosition(Window w, Point2D point,
-                float alignmentX, float alignmentY);
-
         /** Request to recalculate the new position of the security warning for
          * the given window size/location as reported by the native system.
          */
--- a/src/java.desktop/share/classes/sun/awt/HToolkit.java	Wed Sep 26 18:11:00 2018 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,317 +0,0 @@
-/*
- * Copyright (c) 2011, 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 sun.awt;
-
-import java.awt.*;
-import java.awt.datatransfer.Clipboard;
-import java.awt.dnd.DragGestureListener;
-import java.awt.dnd.DragGestureRecognizer;
-import java.awt.dnd.DragSource;
-import java.awt.im.InputMethodHighlight;
-import java.awt.im.spi.InputMethodDescriptor;
-import java.awt.image.ColorModel;
-import java.awt.peer.FramePeer;
-import java.awt.peer.KeyboardFocusManagerPeer;
-import java.awt.peer.SystemTrayPeer;
-import java.awt.peer.TrayIconPeer;
-import java.util.Map;
-import java.util.Properties;
-
-/*
- * HToolkit is a platform independent Toolkit used
- * with the HeadlessToolkit.  It is primarily used
- * in embedded JRE's that do not have sun/awt/X11 classes.
- */
-public final class HToolkit extends SunToolkit implements ComponentFactory {
-
-    private static final KeyboardFocusManagerPeer kfmPeer = new KeyboardFocusManagerPeer() {
-        @Override
-        public void setCurrentFocusedWindow(Window win) {}
-        @Override
-        public Window getCurrentFocusedWindow() { return null; }
-        @Override
-        public void setCurrentFocusOwner(Component comp) {}
-        @Override
-        public Component getCurrentFocusOwner() { return null; }
-        @Override
-        public void clearGlobalFocusOwner(Window activeWindow) {}
-    };
-
-    public HToolkit() {
-    }
-
-    /*
-     * Component peer objects - unsupported.
-     */
-
-    @Override
-    public FramePeer createLightweightFrame(LightweightFrame target)
-        throws HeadlessException {
-        throw new HeadlessException();
-    }
-
-    @Override
-    public KeyboardFocusManagerPeer getKeyboardFocusManagerPeer() {
-        // See 6833019.
-        return kfmPeer;
-    }
-
-    @Override
-    public TrayIconPeer createTrayIcon(TrayIcon target)
-      throws HeadlessException {
-        throw new HeadlessException();
-    }
-
-    @Override
-    public SystemTrayPeer createSystemTray(SystemTray target)
-      throws HeadlessException {
-        throw new HeadlessException();
-    }
-
-    @Override
-    public boolean isTraySupported() {
-        return false;
-    }
-
-    public GlobalCursorManager getGlobalCursorManager()
-        throws HeadlessException {
-        throw new HeadlessException();
-    }
-
-    /*
-     * Headless toolkit - unsupported.
-     */
-    @Override
-    protected void loadSystemColors(int[] systemColors)
-        throws HeadlessException {
-        throw new HeadlessException();
-    }
-
-    @Override
-    public ColorModel getColorModel()
-        throws HeadlessException {
-        throw new HeadlessException();
-    }
-
-    @Override
-    public int getScreenResolution()
-        throws HeadlessException {
-        throw new HeadlessException();
-    }
-
-    @Override
-    public Map<java.awt.font.TextAttribute, ?> mapInputMethodHighlight(
-            InputMethodHighlight highlight)
-        throws HeadlessException {
-        throw new HeadlessException();
-    }
-
-    @Override
-    @Deprecated(since = "10")
-    public int getMenuShortcutKeyMask()
-        throws HeadlessException {
-        throw new HeadlessException();
-    }
-
-    @Override
-    public int getMenuShortcutKeyMaskEx()
-        throws HeadlessException {
-        throw new HeadlessException();
-    }
-
-    @Override
-    public boolean getLockingKeyState(int keyCode)
-        throws UnsupportedOperationException {
-        throw new HeadlessException();
-    }
-
-    @Override
-    public void setLockingKeyState(int keyCode, boolean on)
-        throws UnsupportedOperationException {
-        throw new HeadlessException();
-    }
-
-    @Override
-    public Cursor createCustomCursor(Image cursor, Point hotSpot, String name)
-        throws IndexOutOfBoundsException, HeadlessException {
-        throw new HeadlessException();
-    }
-
-    @Override
-    public Dimension getBestCursorSize(int preferredWidth, int preferredHeight)
-        throws HeadlessException {
-        throw new HeadlessException();
-    }
-
-    @Override
-    public int getMaximumCursorColors()
-        throws HeadlessException {
-        throw new HeadlessException();
-    }
-
-    @Override
-    public <T extends DragGestureRecognizer> T
-        createDragGestureRecognizer(Class<T> abstractRecognizerClass,
-                                    DragSource ds, Component c,
-                                    int srcActions, DragGestureListener dgl)
-    {
-        return null;
-    }
-
-    @Override
-    public Dimension getScreenSize()
-        throws HeadlessException {
-        throw new HeadlessException();
-    }
-
-    @Override
-    public Insets getScreenInsets(GraphicsConfiguration gc)
-        throws HeadlessException {
-        throw new HeadlessException();
-    }
-
-    @Override
-    public void setDynamicLayout(boolean dynamic)
-        throws HeadlessException {
-        throw new HeadlessException();
-    }
-
-    @Override
-    protected boolean isDynamicLayoutSet()
-        throws HeadlessException {
-        throw new HeadlessException();
-    }
-
-    @Override
-    public boolean isDynamicLayoutActive()
-        throws HeadlessException {
-        throw new HeadlessException();
-    }
-
-    @Override
-    public Clipboard getSystemClipboard()
-        throws HeadlessException {
-        throw new HeadlessException();
-    }
-
-    /*
-     * Printing
-     */
-    @Override
-    public PrintJob getPrintJob(Frame frame, String jobtitle,
-        JobAttributes jobAttributes,
-        PageAttributes pageAttributes) {
-        if (frame != null) {
-            // Should never happen
-            throw new HeadlessException();
-        }
-        throw new IllegalArgumentException(
-                "PrintJob not supported in a headless environment");
-    }
-
-    @Override
-    public PrintJob getPrintJob(Frame frame, String doctitle, Properties props)
-    {
-        if (frame != null) {
-            // Should never happen
-            throw new HeadlessException();
-        }
-        throw new IllegalArgumentException(
-                "PrintJob not supported in a headless environment");
-    }
-
-    /*
-     * Headless toolkit - supported.
-     */
-
-    @Override
-    public void sync() {
-        // Do nothing
-    }
-
-    @Override
-    protected boolean syncNativeQueue(final long timeout) {
-        return false;
-    }
-
-    @Override
-    public void beep() {
-        // Send alert character
-        System.out.write(0x07);
-    }
-
-    /*
-     * Modality
-     */
-    @Override
-    public boolean isModalityTypeSupported(Dialog.ModalityType modalityType) {
-        return false;
-    }
-
-    @Override
-    public boolean isModalExclusionTypeSupported(Dialog.ModalExclusionType exclusionType) {
-        return false;
-    }
-
-    @Override
-    public boolean isDesktopSupported() {
-        return false;
-    }
-
-    @Override
-    public boolean isTaskbarSupported() {
-        return false;
-    }
-
-    public boolean isWindowOpacityControlSupported() {
-        return false;
-    }
-
-    @Override
-    public boolean isWindowShapingSupported() {
-        return false;
-    }
-
-    @Override
-    public boolean isWindowTranslucencySupported() {
-        return false;
-    }
-
-    @Override
-    public  void grab(Window w) { }
-
-    @Override
-    public void ungrab(Window w) { }
-
-    protected boolean syncNativeQueue() { return false; }
-
-    @Override
-    public InputMethodDescriptor getInputMethodAdapterDescriptor()
-        throws AWTException
-    {
-        return (InputMethodDescriptor)null;
-    }
-}
--- a/src/java.desktop/share/classes/sun/font/CMap.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/java.desktop/share/classes/sun/font/CMap.java	Mon Oct 01 09:56:45 2018 +0100
@@ -566,6 +566,7 @@
 
         char getGlyph(int charCode) {
 
+            final int origCharCode = charCode;
             int index = 0;
             char glyphCode = 0;
 
@@ -637,8 +638,8 @@
                     }
                 }
             }
-            if (glyphCode != 0) {
-            //System.err.println("cc="+Integer.toHexString((int)charCode) + " gc="+(int)glyphCode);
+            if (glyphCode == 0) {
+              glyphCode = getFormatCharGlyph(origCharCode);
             }
             return glyphCode;
         }
@@ -804,6 +805,7 @@
         }
 
         char getGlyph(int charCode) {
+            final int origCharCode = charCode;
             int controlGlyph = getControlCodeGlyph(charCode, true);
             if (controlGlyph >= 0) {
                 return (char)controlGlyph;
@@ -859,7 +861,7 @@
                     return glyphCode;
                 }
             }
-            return 0;
+            return getFormatCharGlyph(origCharCode);
         }
     }
 
@@ -883,6 +885,7 @@
          }
 
          char getGlyph(int charCode) {
+            final int origCharCode = charCode;
             int controlGlyph = getControlCodeGlyph(charCode, true);
             if (controlGlyph >= 0) {
                 return (char)controlGlyph;
@@ -894,7 +897,7 @@
 
              charCode -= firstCode;
              if (charCode < 0 || charCode >= entryCount) {
-                  return 0;
+                  return getFormatCharGlyph(origCharCode);
              } else {
                   return glyphIdArray[charCode];
              }
@@ -1032,6 +1035,7 @@
         }
 
         char getGlyph(int charCode) {
+            final int origCharCode = charCode;
             int controlGlyph = getControlCodeGlyph(charCode, false);
             if (controlGlyph >= 0) {
                 return (char)controlGlyph;
@@ -1057,7 +1061,7 @@
                     (startGlyphID[range] + (charCode - startCharCode[range]));
             }
 
-            return 0;
+            return getFormatCharGlyph(origCharCode);
         }
 
     }
@@ -1079,16 +1083,21 @@
             case 0x000a:
             case 0x000d: return CharToGlyphMapper.INVISIBLE_GLYPH_ID;
             }
-        } else if (charCode >= 0x200c) {
+         } else if (noSurrogates && charCode >= 0xFFFF) {
+            return 0;
+        }
+        return -1;
+    }
+
+    final char getFormatCharGlyph(int charCode) {
+        if (charCode >= 0x200c) {
             if ((charCode <= 0x200f) ||
                 (charCode >= 0x2028 && charCode <= 0x202e) ||
                 (charCode >= 0x206a && charCode <= 0x206f)) {
-                return CharToGlyphMapper.INVISIBLE_GLYPH_ID;
-            } else if (noSurrogates && charCode >= 0xFFFF) {
-                return 0;
+                return (char)CharToGlyphMapper.INVISIBLE_GLYPH_ID;
             }
         }
-        return -1;
+        return 0;
     }
 
     static class UVS {
--- a/src/java.desktop/share/classes/sun/font/SunFontManager.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/java.desktop/share/classes/sun/font/SunFontManager.java	Mon Oct 01 09:56:45 2018 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2008, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 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
@@ -2740,7 +2740,7 @@
                 new java.security.PrivilegedAction<Object>() {
                         public Object run() {
                             SecurityManager sm = System.getSecurityManager();
-                            return sm instanceof sun.applet.AppletSecurity;
+                            return sm instanceof sun.awt.AWTSecurityManager;
                         }
                     });
         return appletSM.booleanValue();
--- a/src/java.desktop/share/classes/sun/font/SunLayoutEngine.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/java.desktop/share/classes/sun/font/SunLayoutEngine.java	Mon Oct 01 09:56:45 2018 +0100
@@ -35,6 +35,7 @@
 import java.lang.ref.SoftReference;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.Locale;
+import java.util.WeakHashMap;
 
 /*
  * different ways to do this
@@ -148,17 +149,30 @@
         this.key = key;
     }
 
+    static WeakHashMap<Font2D, Boolean> aatInfo = new WeakHashMap<>();
+
     private boolean isAAT(Font2D font) {
+       Boolean aatObj;
+       synchronized (aatInfo) {
+           aatObj = aatInfo.get(font);
+       }
+       if (aatObj != null) {
+          return aatObj.booleanValue();
+       }
+       boolean aat = false;
        if (font instanceof TrueTypeFont) {
            TrueTypeFont ttf = (TrueTypeFont)font;
-           return ttf.getDirectoryEntry(TrueTypeFont.morxTag) != null ||
+           aat =  ttf.getDirectoryEntry(TrueTypeFont.morxTag) != null ||
                   ttf.getDirectoryEntry(TrueTypeFont.mortTag) != null;
        } else if (font instanceof PhysicalFont) {
            PhysicalFont pf = (PhysicalFont)font;
-           return pf.getTableBytes(TrueTypeFont.morxTag) != null ||
+           aat =  pf.getTableBytes(TrueTypeFont.morxTag) != null ||
                   pf.getTableBytes(TrueTypeFont.mortTag) != null;
        }
-       return false;
+       synchronized (aatInfo) {
+           aatInfo.put(font, Boolean.valueOf(aat));
+       }
+       return aat;
     }
 
     public void layout(FontStrikeDesc desc, float[] mat, float ptSize, int gmask,
--- a/src/java.desktop/share/classes/sun/java2d/marlin/DMarlinRenderingEngine.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/java.desktop/share/classes/sun/java2d/marlin/DMarlinRenderingEngine.java	Mon Oct 01 09:56:45 2018 +0100
@@ -31,6 +31,7 @@
 import java.awt.geom.Path2D;
 import java.awt.geom.PathIterator;
 import java.security.AccessController;
+import java.util.Arrays;
 import sun.awt.geom.PathConsumer2D;
 import static sun.java2d.marlin.MarlinUtils.logInfo;
 import sun.java2d.ReentrantContextProvider;
@@ -334,7 +335,6 @@
 
         int dashLen = -1;
         boolean recycleDashes = false;
-        double scale = 1.0d;
         double[] dashesD = null;
 
         // Ensure converting dashes to double precision:
@@ -375,7 +375,7 @@
             // a*b == -c*d && a*a+c*c == b*b+d*d. In the actual check below, we
             // leave a bit of room for error.
             if (nearZero(a*b + c*d) && nearZero(a*a + c*c - (b*b + d*d))) {
-                scale =  Math.sqrt(a*a + c*c);
+                final double scale = Math.sqrt(a*a + c*c);
 
                 if (dashesD != null) {
                     for (int i = 0; i < dashLen; i++) {
@@ -427,7 +427,7 @@
         pc2d = transformerPC2D.deltaTransformConsumer(pc2d, strokerat);
 
         // stroker will adjust the clip rectangle (width / miter limit):
-        pc2d = rdrCtx.stroker.init(pc2d, width, caps, join, miterlimit, scale,
+        pc2d = rdrCtx.stroker.init(pc2d, width, caps, join, miterlimit,
                 (dashesD == null));
 
         // Curve Monotizer:
@@ -834,10 +834,26 @@
                 // Define the initial clip bounds:
                 final double[] clipRect = rdrCtx.clipRect;
 
-                clipRect[0] = clip.getLoY();
-                clipRect[1] = clip.getLoY() + clip.getHeight();
-                clipRect[2] = clip.getLoX();
-                clipRect[3] = clip.getLoX() + clip.getWidth();
+                // Adjust the clipping rectangle with the renderer offsets
+                final double rdrOffX = DRenderer.RDR_OFFSET_X;
+                final double rdrOffY = DRenderer.RDR_OFFSET_Y;
+
+                // add a small rounding error:
+                final double margin = 1e-3d;
+
+                clipRect[0] = clip.getLoY()
+                                - margin + rdrOffY;
+                clipRect[1] = clip.getLoY() + clip.getHeight()
+                                + margin + rdrOffY;
+                clipRect[2] = clip.getLoX()
+                                - margin + rdrOffX;
+                clipRect[3] = clip.getLoX() + clip.getWidth()
+                                + margin + rdrOffX;
+
+                if (MarlinConst.DO_LOG_CLIP) {
+                    MarlinUtils.logInfo("clipRect (clip): "
+                                        + Arrays.toString(rdrCtx.clipRect));
+                }
 
                 // Enable clipping:
                 rdrCtx.doClip = true;
--- a/src/java.desktop/share/classes/sun/java2d/marlin/DRendererContext.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/java.desktop/share/classes/sun/java2d/marlin/DRendererContext.java	Mon Oct 01 09:56:45 2018 +0100
@@ -85,6 +85,8 @@
     boolean closedPath = false;
     // clip rectangle (ymin, ymax, xmin, xmax):
     final double[] clipRect = new double[4];
+    // clip inverse scale (mean) to adjust length checks
+    double clipInvScale = 0.0d;
     // CurveBasicMonotonizer instance
     final CurveBasicMonotonizer monotonizer;
     // CurveClipSplitter instance
@@ -105,7 +107,6 @@
 
     final PathConsumer2DAdapter p2dAdapter = new PathConsumer2DAdapter();
 
-
     /**
      * Constructor
      *
@@ -162,6 +163,7 @@
         stroking   = 0;
         doClip     = false;
         closedPath = false;
+        clipInvScale = 0.0d;
 
         // if context is maked as DIRTY:
         if (dirty) {
--- a/src/java.desktop/share/classes/sun/java2d/marlin/DStroker.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/java.desktop/share/classes/sun/java2d/marlin/DStroker.java	Mon Oct 01 09:56:45 2018 +0100
@@ -139,7 +139,6 @@
      * <code>JOIN_MITER</code>, <code>JOIN_ROUND</code> or
      * <code>JOIN_BEVEL</code>.
      * @param miterLimit the desired miter limit
-     * @param scale scaling factor applied to clip boundaries
      * @param subdivideCurves true to indicate to subdivide curves, false if dasher does
      * @return this instance
      */
@@ -148,7 +147,6 @@
                   final int capStyle,
                   final int joinStyle,
                   final double miterLimit,
-                  final double scale,
                   final boolean subdivideCurves)
     {
         this.out = pc2d;
@@ -169,7 +167,6 @@
 
         if (rdrCtx.doClip) {
             // Adjust the clipping rectangle with the stroker margin (miter limit, width)
-            double rdrOffX = 0.0d, rdrOffY = 0.0d;
             double margin = lineWidth2;
 
             if (capStyle == CAP_SQUARE) {
@@ -178,23 +175,21 @@
             if ((joinStyle == JOIN_MITER) && (margin < limit)) {
                 margin = limit;
             }
-            if (scale != 1.0d) {
-                margin *= scale;
-                rdrOffX = scale * DRenderer.RDR_OFFSET_X;
-                rdrOffY = scale * DRenderer.RDR_OFFSET_Y;
-            }
-            // add a small rounding error:
-            margin += 1e-3d;
 
             // bounds as half-open intervals: minX <= x < maxX and minY <= y < maxY
             // adjust clip rectangle (ymin, ymax, xmin, xmax):
             final double[] _clipRect = rdrCtx.clipRect;
-            _clipRect[0] -= margin - rdrOffY;
-            _clipRect[1] += margin + rdrOffY;
-            _clipRect[2] -= margin - rdrOffX;
-            _clipRect[3] += margin + rdrOffX;
+            _clipRect[0] -= margin;
+            _clipRect[1] += margin;
+            _clipRect[2] -= margin;
+            _clipRect[3] += margin;
             this.clipRect = _clipRect;
 
+            if (MarlinConst.DO_LOG_CLIP) {
+                MarlinUtils.logInfo("clipRect (stroker): "
+                                    + Arrays.toString(rdrCtx.clipRect));
+            }
+
             // initialize curve splitter here for stroker & dasher:
             if (DO_CLIP_SUBDIVIDER) {
                 subdivide = subdivideCurves;
@@ -304,13 +299,9 @@
         // If it is >=0, we know that abs(ext) is <= 90 degrees, so we only
         // need 1 curve to approximate the circle section that joins omx,omy
         // and mx,my.
-        final int numCurves = (cosext >= 0.0d) ? 1 : 2;
-
-        switch (numCurves) {
-        case 1:
+        if (cosext >= 0.0d) {
             drawBezApproxForArc(cx, cy, omx, omy, mx, my, rev);
-            break;
-        case 2:
+        } else {
             // we need to split the arc into 2 arcs spanning the same angle.
             // The point we want will be one of the 2 intersections of the
             // perpendicular bisector of the chord (omx,omy)->(mx,my) and the
@@ -339,8 +330,6 @@
             }
             drawBezApproxForArc(cx, cy, omx, omy, mmx, mmy, rev);
             drawBezApproxForArc(cx, cy, mmx, mmy, mx, my, rev);
-            break;
-        default:
         }
     }
 
--- a/src/java.desktop/share/classes/sun/java2d/marlin/DTransformingPathConsumer2D.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/java.desktop/share/classes/sun/java2d/marlin/DTransformingPathConsumer2D.java	Mon Oct 01 09:56:45 2018 +0100
@@ -119,44 +119,56 @@
                 // Scale only
                 if (rdrCtx.doClip) {
                     // adjust clip rectangle (ymin, ymax, xmin, xmax):
-                    adjustClipScale(rdrCtx.clipRect, mxx, myy);
+                    rdrCtx.clipInvScale = adjustClipScale(rdrCtx.clipRect,
+                        mxx, myy);
                 }
                 return dt_DeltaScaleFilter.init(out, mxx, myy);
             }
         } else {
             if (rdrCtx.doClip) {
                 // adjust clip rectangle (ymin, ymax, xmin, xmax):
-                adjustClipInverseDelta(rdrCtx.clipRect, mxx, mxy, myx, myy);
+                rdrCtx.clipInvScale = adjustClipInverseDelta(rdrCtx.clipRect,
+                    mxx, mxy, myx, myy);
             }
             return dt_DeltaTransformFilter.init(out, mxx, mxy, myx, myy);
         }
     }
 
-    private static void adjustClipOffset(final double[] clipRect) {
-        clipRect[0] += Renderer.RDR_OFFSET_Y;
-        clipRect[1] += Renderer.RDR_OFFSET_Y;
-        clipRect[2] += Renderer.RDR_OFFSET_X;
-        clipRect[3] += Renderer.RDR_OFFSET_X;
+    private static double adjustClipScale(final double[] clipRect,
+                                          final double mxx, final double myy)
+    {
+        // Adjust the clipping rectangle (iv_DeltaScaleFilter):
+        final double scaleY = 1.0d / myy;
+        clipRect[0] *= scaleY;
+        clipRect[1] *= scaleY;
+
+        if (clipRect[1] < clipRect[0]) {
+            double tmp = clipRect[0];
+            clipRect[0] = clipRect[1];
+            clipRect[1] = tmp;
+        }
+
+        final double scaleX = 1.0d / mxx;
+        clipRect[2] *= scaleX;
+        clipRect[3] *= scaleX;
+
+        if (clipRect[3] < clipRect[2]) {
+            double tmp = clipRect[2];
+            clipRect[2] = clipRect[3];
+            clipRect[3] = tmp;
+        }
+
+        if (MarlinConst.DO_LOG_CLIP) {
+                MarlinUtils.logInfo("clipRect (ClipScale): "
+                                    + Arrays.toString(clipRect));
+        }
+        return 0.5d * (Math.abs(scaleX) + Math.abs(scaleY));
     }
 
-    private static void adjustClipScale(final double[] clipRect,
-                                        final double mxx, final double myy)
+    private static double adjustClipInverseDelta(final double[] clipRect,
+                                                 final double mxx, final double mxy,
+                                                 final double myx, final double myy)
     {
-        adjustClipOffset(clipRect);
-
-        // Adjust the clipping rectangle (iv_DeltaScaleFilter):
-        clipRect[0] /= myy;
-        clipRect[1] /= myy;
-        clipRect[2] /= mxx;
-        clipRect[3] /= mxx;
-    }
-
-    private static void adjustClipInverseDelta(final double[] clipRect,
-                                               final double mxx, final double mxy,
-                                               final double myx, final double myy)
-    {
-        adjustClipOffset(clipRect);
-
         // Adjust the clipping rectangle (iv_DeltaTransformFilter):
         final double det = mxx * myy - mxy * myx;
         final double imxx =  myy / det;
@@ -198,6 +210,16 @@
         clipRect[1] = ymax;
         clipRect[2] = xmin;
         clipRect[3] = xmax;
+
+        if (MarlinConst.DO_LOG_CLIP) {
+                MarlinUtils.logInfo("clipRect (ClipInverseDelta): "
+                                    + Arrays.toString(clipRect));
+        }
+
+        final double scaleX = Math.sqrt(imxx * imxx + imxy * imxy);
+        final double scaleY = Math.sqrt(imyx * imyx + imyy * imyy);
+
+        return 0.5d * (scaleX + scaleY);
     }
 
     DPathConsumer2D inverseDeltaTransformConsumer(DPathConsumer2D out,
@@ -215,7 +237,7 @@
             if (mxx == 1.0d && myy == 1.0d) {
                 return out;
             } else {
-                return iv_DeltaScaleFilter.init(out, 1.0d/mxx, 1.0d/myy);
+                return iv_DeltaScaleFilter.init(out, 1.0d / mxx, 1.0d / myy);
             }
         } else {
             final double det = mxx * myy - mxy * myx;
@@ -532,19 +554,6 @@
         PathClipFilter init(final DPathConsumer2D out) {
             this.out = out;
 
-            // Adjust the clipping rectangle with the renderer offsets
-            final double rdrOffX = DRenderer.RDR_OFFSET_X;
-            final double rdrOffY = DRenderer.RDR_OFFSET_Y;
-
-            // add a small rounding error:
-            final double margin = 1e-3d;
-
-            final double[] _clipRect = this.clipRect;
-            _clipRect[0] -= margin - rdrOffY;
-            _clipRect[1] += margin + rdrOffY;
-            _clipRect[2] -= margin - rdrOffX;
-            _clipRect[3] += margin + rdrOffX;
-
             if (MarlinConst.DO_CLIP_SUBDIVIDER) {
                 // adjust padded clip rectangle:
                 curveSplitter.init();
@@ -867,6 +876,11 @@
 
         private static final int MAX_N_CURVES = 3 * 4;
 
+        private final DRendererContext rdrCtx;
+
+        // scaled length threshold:
+        private double minLength;
+
         // clip rectangle (ymin, ymax, xmin, xmax):
         final double[] clipRect;
 
@@ -884,12 +898,23 @@
         private final DCurve curve;
 
         CurveClipSplitter(final DRendererContext rdrCtx) {
+            this.rdrCtx = rdrCtx;
             this.clipRect = rdrCtx.clipRect;
             this.curve = rdrCtx.curve;
         }
 
         void init() {
             this.init_clipRectPad = true;
+
+            if (DO_CHECK_LENGTH) {
+                this.minLength = (this.rdrCtx.clipInvScale == 0.0d) ? LEN_TH
+                                    : (LEN_TH * this.rdrCtx.clipInvScale);
+
+                if (MarlinConst.DO_LOG_CLIP) {
+                    MarlinUtils.logInfo("CurveClipSplitter.minLength = "
+                                            + minLength);
+                }
+            }
         }
 
         private void initPaddedClip() {
@@ -906,7 +931,7 @@
 
             if (TRACE) {
                 MarlinUtils.logInfo("clip: X [" + _clipRectPad[2] + " .. " + _clipRectPad[3] +"] "
-                                        + "Y ["+ _clipRectPad[0] + " .. " + _clipRectPad[1] +"]");
+                                        + "Y [" + _clipRectPad[0] + " .. " + _clipRectPad[1] +"]");
             }
         }
 
@@ -919,7 +944,7 @@
                 MarlinUtils.logInfo("divLine P0(" + x0 + ", " + y0 + ") P1(" + x1 + ", " + y1 + ")");
             }
 
-            if (DO_CHECK_LENGTH && DHelpers.fastLineLen(x0, y0, x1, y1) <= LEN_TH) {
+            if (DO_CHECK_LENGTH && DHelpers.fastLineLen(x0, y0, x1, y1) <= minLength) {
                 return false;
             }
 
@@ -940,7 +965,7 @@
                 MarlinUtils.logInfo("divQuad P0(" + x0 + ", " + y0 + ") P1(" + x1 + ", " + y1 + ") P2(" + x2 + ", " + y2 + ")");
             }
 
-            if (DO_CHECK_LENGTH && DHelpers.fastQuadLen(x0, y0, x1, y1, x2, y2) <= LEN_TH) {
+            if (DO_CHECK_LENGTH && DHelpers.fastQuadLen(x0, y0, x1, y1, x2, y2) <= minLength) {
                 return false;
             }
 
@@ -963,7 +988,7 @@
                 MarlinUtils.logInfo("divCurve P0(" + x0 + ", " + y0 + ") P1(" + x1 + ", " + y1 + ") P2(" + x2 + ", " + y2 + ") P3(" + x3 + ", " + y3 + ")");
             }
 
-            if (DO_CHECK_LENGTH && DHelpers.fastCurvelen(x0, y0, x1, y1, x2, y2, x3, y3) <= LEN_TH) {
+            if (DO_CHECK_LENGTH && DHelpers.fastCurvelen(x0, y0, x1, y1, x2, y2, x3, y3) <= minLength) {
                 return false;
             }
 
@@ -991,8 +1016,8 @@
                                                         outCodeOR, clipRectPad);
 
             if (TRACE) {
-                MarlinUtils.logInfo("nSplits: "+ nSplits);
-                MarlinUtils.logInfo("subTs: "+Arrays.toString(Arrays.copyOfRange(subTs, 0, nSplits)));
+                MarlinUtils.logInfo("nSplits: " + nSplits);
+                MarlinUtils.logInfo("subTs: " + Arrays.toString(Arrays.copyOfRange(subTs, 0, nSplits)));
             }
             if (nSplits == 0) {
                 // only curve support shortcut
@@ -1010,7 +1035,7 @@
 
             for (int i = 0, off = 0; i <= nSplits; i++, off += type) {
                 if (TRACE) {
-                    MarlinUtils.logInfo("Part Curve "+Arrays.toString(Arrays.copyOfRange(mid, off, off + type)));
+                    MarlinUtils.logInfo("Part Curve " + Arrays.toString(Arrays.copyOfRange(mid, off, off + type)));
                 }
                 emitCurrent(type, mid, off, out);
             }
--- a/src/java.desktop/share/classes/sun/java2d/marlin/MarlinConst.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/java.desktop/share/classes/sun/java2d/marlin/MarlinConst.java	Mon Oct 01 09:56:45 2018 +0100
@@ -82,11 +82,11 @@
 
     static final boolean DO_CLIP_SUBDIVIDER = MarlinProperties.isDoClipSubdivider();
 
-    // flag to enable logs related bounds checks
+    // flag to enable logs related to bounds checks
     static final boolean DO_LOG_BOUNDS = ENABLE_LOGS && false;
 
-    // flag to enable float precision correction
-    static final boolean DO_FIX_FLOAT_PREC = true;
+    // flag to enable logs related to clip rect
+    static final boolean DO_LOG_CLIP = ENABLE_LOGS && false;
 
     // Initial Array sizing (initial context capacity) ~ 450K
 
--- a/src/java.desktop/share/classes/sun/java2d/marlin/MarlinRenderingEngine.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/java.desktop/share/classes/sun/java2d/marlin/MarlinRenderingEngine.java	Mon Oct 01 09:56:45 2018 +0100
@@ -31,6 +31,7 @@
 import java.awt.geom.Path2D;
 import java.awt.geom.PathIterator;
 import java.security.AccessController;
+import java.util.Arrays;
 import static sun.java2d.marlin.MarlinUtils.logInfo;
 import sun.awt.geom.PathConsumer2D;
 import sun.java2d.ReentrantContextProvider;
@@ -333,7 +334,6 @@
 
         int dashLen = -1;
         boolean recycleDashes = false;
-        float scale = 1.0f;
 
         if (at != null && !at.isIdentity()) {
             final double a = at.getScaleX();
@@ -366,7 +366,7 @@
             // a*b == -c*d && a*a+c*c == b*b+d*d. In the actual check below, we
             // leave a bit of room for error.
             if (nearZero(a*b + c*d) && nearZero(a*a + c*c - (b*b + d*d))) {
-                scale = (float) Math.sqrt(a*a + c*c);
+                final float scale = (float) Math.sqrt(a*a + c*c);
 
                 if (dashes != null) {
                     recycleDashes = true;
@@ -421,7 +421,7 @@
         pc2d = transformerPC2D.deltaTransformConsumer(pc2d, strokerat);
 
         // stroker will adjust the clip rectangle (width / miter limit):
-        pc2d = rdrCtx.stroker.init(pc2d, width, caps, join, miterlimit, scale,
+        pc2d = rdrCtx.stroker.init(pc2d, width, caps, join, miterlimit,
                 (dashes == null));
 
         // Curve Monotizer:
@@ -831,10 +831,26 @@
                 // Define the initial clip bounds:
                 final float[] clipRect = rdrCtx.clipRect;
 
-                clipRect[0] = clip.getLoY();
-                clipRect[1] = clip.getLoY() + clip.getHeight();
-                clipRect[2] = clip.getLoX();
-                clipRect[3] = clip.getLoX() + clip.getWidth();
+                // Adjust the clipping rectangle with the renderer offsets
+                final float rdrOffX = Renderer.RDR_OFFSET_X;
+                final float rdrOffY = Renderer.RDR_OFFSET_Y;
+
+                // add a small rounding error:
+                final float margin = 1e-3f;
+
+                clipRect[0] = clip.getLoY()
+                                - margin + rdrOffY;
+                clipRect[1] = clip.getLoY() + clip.getHeight()
+                                + margin + rdrOffY;
+                clipRect[2] = clip.getLoX()
+                                - margin + rdrOffX;
+                clipRect[3] = clip.getLoX() + clip.getWidth()
+                                + margin + rdrOffX;
+
+                if (MarlinConst.DO_LOG_CLIP) {
+                    MarlinUtils.logInfo("clipRect (clip): "
+                                        + Arrays.toString(rdrCtx.clipRect));
+                }
 
                 // Enable clipping:
                 rdrCtx.doClip = true;
--- a/src/java.desktop/share/classes/sun/java2d/marlin/RendererContext.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/java.desktop/share/classes/sun/java2d/marlin/RendererContext.java	Mon Oct 01 09:56:45 2018 +0100
@@ -85,6 +85,8 @@
     boolean closedPath = false;
     // clip rectangle (ymin, ymax, xmin, xmax):
     final float[] clipRect = new float[4];
+    // clip inverse scale (mean) to adjust length checks
+    float clipInvScale = 0.0f;
     // CurveBasicMonotonizer instance
     final CurveBasicMonotonizer monotonizer;
     // CurveClipSplitter instance
@@ -159,6 +161,7 @@
         stroking   = 0;
         doClip     = false;
         closedPath = false;
+        clipInvScale = 0.0f;
 
         // if context is maked as DIRTY:
         if (dirty) {
--- a/src/java.desktop/share/classes/sun/java2d/marlin/Stroker.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/java.desktop/share/classes/sun/java2d/marlin/Stroker.java	Mon Oct 01 09:56:45 2018 +0100
@@ -141,7 +141,6 @@
      * <code>JOIN_MITER</code>, <code>JOIN_ROUND</code> or
      * <code>JOIN_BEVEL</code>.
      * @param miterLimit the desired miter limit
-     * @param scale scaling factor applied to clip boundaries
      * @param subdivideCurves true to indicate to subdivide curves, false if dasher does
      * @return this instance
      */
@@ -150,7 +149,6 @@
                  final int capStyle,
                  final int joinStyle,
                  final float miterLimit,
-                 final float scale,
                  final boolean subdivideCurves)
     {
         this.out = pc2d;
@@ -171,7 +169,6 @@
 
         if (rdrCtx.doClip) {
             // Adjust the clipping rectangle with the stroker margin (miter limit, width)
-            float rdrOffX = 0.0f, rdrOffY = 0.0f;
             float margin = lineWidth2;
 
             if (capStyle == CAP_SQUARE) {
@@ -180,23 +177,21 @@
             if ((joinStyle == JOIN_MITER) && (margin < limit)) {
                 margin = limit;
             }
-            if (scale != 1.0f) {
-                margin *= scale;
-                rdrOffX = scale * Renderer.RDR_OFFSET_X;
-                rdrOffY = scale * Renderer.RDR_OFFSET_Y;
-            }
-            // add a small rounding error:
-            margin += 1e-3f;
 
             // bounds as half-open intervals: minX <= x < maxX and minY <= y < maxY
             // adjust clip rectangle (ymin, ymax, xmin, xmax):
             final float[] _clipRect = rdrCtx.clipRect;
-            _clipRect[0] -= margin - rdrOffY;
-            _clipRect[1] += margin + rdrOffY;
-            _clipRect[2] -= margin - rdrOffX;
-            _clipRect[3] += margin + rdrOffX;
+            _clipRect[0] -= margin;
+            _clipRect[1] += margin;
+            _clipRect[2] -= margin;
+            _clipRect[3] += margin;
             this.clipRect = _clipRect;
 
+            if (MarlinConst.DO_LOG_CLIP) {
+                MarlinUtils.logInfo("clipRect (stroker): "
+                                    + Arrays.toString(rdrCtx.clipRect));
+            }
+
             // initialize curve splitter here for stroker & dasher:
             if (DO_CLIP_SUBDIVIDER) {
                 subdivide = subdivideCurves;
@@ -306,13 +301,9 @@
         // If it is >=0, we know that abs(ext) is <= 90 degrees, so we only
         // need 1 curve to approximate the circle section that joins omx,omy
         // and mx,my.
-        final int numCurves = (cosext >= 0.0f) ? 1 : 2;
-
-        switch (numCurves) {
-        case 1:
+        if (cosext >= 0.0f) {
             drawBezApproxForArc(cx, cy, omx, omy, mx, my, rev);
-            break;
-        case 2:
+        } else {
             // we need to split the arc into 2 arcs spanning the same angle.
             // The point we want will be one of the 2 intersections of the
             // perpendicular bisector of the chord (omx,omy)->(mx,my) and the
@@ -341,8 +332,6 @@
             }
             drawBezApproxForArc(cx, cy, omx, omy, mmx, mmy, rev);
             drawBezApproxForArc(cx, cy, mmx, mmy, mx, my, rev);
-            break;
-        default:
         }
     }
 
--- a/src/java.desktop/share/classes/sun/java2d/marlin/TransformingPathConsumer2D.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/java.desktop/share/classes/sun/java2d/marlin/TransformingPathConsumer2D.java	Mon Oct 01 09:56:45 2018 +0100
@@ -120,44 +120,56 @@
                 // Scale only
                 if (rdrCtx.doClip) {
                     // adjust clip rectangle (ymin, ymax, xmin, xmax):
-                    adjustClipScale(rdrCtx.clipRect, mxx, myy);
+                    rdrCtx.clipInvScale = adjustClipScale(rdrCtx.clipRect,
+                        mxx, myy);
                 }
                 return dt_DeltaScaleFilter.init(out, mxx, myy);
             }
         } else {
             if (rdrCtx.doClip) {
                 // adjust clip rectangle (ymin, ymax, xmin, xmax):
-                adjustClipInverseDelta(rdrCtx.clipRect, mxx, mxy, myx, myy);
+                rdrCtx.clipInvScale = adjustClipInverseDelta(rdrCtx.clipRect,
+                    mxx, mxy, myx, myy);
             }
             return dt_DeltaTransformFilter.init(out, mxx, mxy, myx, myy);
         }
     }
 
-    private static void adjustClipOffset(final float[] clipRect) {
-        clipRect[0] += Renderer.RDR_OFFSET_Y;
-        clipRect[1] += Renderer.RDR_OFFSET_Y;
-        clipRect[2] += Renderer.RDR_OFFSET_X;
-        clipRect[3] += Renderer.RDR_OFFSET_X;
+    private static float adjustClipScale(final float[] clipRect,
+                                         final float mxx, final float myy)
+    {
+        // Adjust the clipping rectangle (iv_DeltaScaleFilter):
+        final float scaleY = 1.0f / myy;
+        clipRect[0] *= scaleY;
+        clipRect[1] *= scaleY;
+
+        if (clipRect[1] < clipRect[0]) {
+            float tmp = clipRect[0];
+            clipRect[0] = clipRect[1];
+            clipRect[1] = tmp;
+        }
+
+        final float scaleX = 1.0f / mxx;
+        clipRect[2] *= scaleX;
+        clipRect[3] *= scaleX;
+
+        if (clipRect[3] < clipRect[2]) {
+            float tmp = clipRect[2];
+            clipRect[2] = clipRect[3];
+            clipRect[3] = tmp;
+        }
+
+        if (MarlinConst.DO_LOG_CLIP) {
+                MarlinUtils.logInfo("clipRect (ClipScale): "
+                                    + Arrays.toString(clipRect));
+        }
+        return 0.5f * (Math.abs(scaleX) + Math.abs(scaleY));
     }
 
-    private static void adjustClipScale(final float[] clipRect,
-                                        final float mxx, final float myy)
+    private static float adjustClipInverseDelta(final float[] clipRect,
+                                                final float mxx, final float mxy,
+                                                final float myx, final float myy)
     {
-        adjustClipOffset(clipRect);
-
-        // Adjust the clipping rectangle (iv_DeltaScaleFilter):
-        clipRect[0] /= myy;
-        clipRect[1] /= myy;
-        clipRect[2] /= mxx;
-        clipRect[3] /= mxx;
-    }
-
-    private static void adjustClipInverseDelta(final float[] clipRect,
-                                               final float mxx, final float mxy,
-                                               final float myx, final float myy)
-    {
-        adjustClipOffset(clipRect);
-
         // Adjust the clipping rectangle (iv_DeltaTransformFilter):
         final float det = mxx * myy - mxy * myx;
         final float imxx =  myy / det;
@@ -199,6 +211,16 @@
         clipRect[1] = ymax;
         clipRect[2] = xmin;
         clipRect[3] = xmax;
+
+        if (MarlinConst.DO_LOG_CLIP) {
+                MarlinUtils.logInfo("clipRect (ClipInverseDelta): "
+                                    + Arrays.toString(clipRect));
+        }
+
+        final float scaleX = (float) Math.sqrt(imxx * imxx + imxy * imxy);
+        final float scaleY = (float) Math.sqrt(imyx * imyx + imyy * imyy);
+
+        return 0.5f * (scaleX + scaleY);
     }
 
     PathConsumer2D inverseDeltaTransformConsumer(PathConsumer2D out,
@@ -216,7 +238,7 @@
             if (mxx == 1.0f && myy == 1.0f) {
                 return out;
             } else {
-                return iv_DeltaScaleFilter.init(out, 1.0f/mxx, 1.0f/myy);
+                return iv_DeltaScaleFilter.init(out, 1.0f / mxx, 1.0f / myy);
             }
         } else {
             final float det = mxx * myy - mxy * myx;
@@ -533,19 +555,6 @@
         PathClipFilter init(final PathConsumer2D out) {
             this.out = out;
 
-            // Adjust the clipping rectangle with the renderer offsets
-            final float rdrOffX = Renderer.RDR_OFFSET_X;
-            final float rdrOffY = Renderer.RDR_OFFSET_Y;
-
-            // add a small rounding error:
-            final float margin = 1e-3f;
-
-            final float[] _clipRect = this.clipRect;
-            _clipRect[0] -= margin - rdrOffY;
-            _clipRect[1] += margin + rdrOffY;
-            _clipRect[2] -= margin - rdrOffX;
-            _clipRect[3] += margin + rdrOffX;
-
             if (MarlinConst.DO_CLIP_SUBDIVIDER) {
                 // adjust padded clip rectangle:
                 curveSplitter.init();
@@ -868,6 +877,11 @@
 
         private static final int MAX_N_CURVES = 3 * 4;
 
+        private final RendererContext rdrCtx;
+
+        // scaled length threshold:
+        private float minLength;
+
         // clip rectangle (ymin, ymax, xmin, xmax):
         final float[] clipRect;
 
@@ -885,12 +899,23 @@
         private final Curve curve;
 
         CurveClipSplitter(final RendererContext rdrCtx) {
+            this.rdrCtx = rdrCtx;
             this.clipRect = rdrCtx.clipRect;
             this.curve = rdrCtx.curve;
         }
 
         void init() {
             this.init_clipRectPad = true;
+
+            if (DO_CHECK_LENGTH) {
+                this.minLength = (this.rdrCtx.clipInvScale == 0.0f) ? LEN_TH
+                                    : (LEN_TH * this.rdrCtx.clipInvScale);
+
+                if (MarlinConst.DO_LOG_CLIP) {
+                    MarlinUtils.logInfo("CurveClipSplitter.minLength = "
+                                            + minLength);
+                }
+            }
         }
 
         private void initPaddedClip() {
@@ -907,7 +932,7 @@
 
             if (TRACE) {
                 MarlinUtils.logInfo("clip: X [" + _clipRectPad[2] + " .. " + _clipRectPad[3] +"] "
-                                        + "Y ["+ _clipRectPad[0] + " .. " + _clipRectPad[1] +"]");
+                                        + "Y [" + _clipRectPad[0] + " .. " + _clipRectPad[1] +"]");
             }
         }
 
@@ -920,7 +945,7 @@
                 MarlinUtils.logInfo("divLine P0(" + x0 + ", " + y0 + ") P1(" + x1 + ", " + y1 + ")");
             }
 
-            if (DO_CHECK_LENGTH && Helpers.fastLineLen(x0, y0, x1, y1) <= LEN_TH) {
+            if (DO_CHECK_LENGTH && Helpers.fastLineLen(x0, y0, x1, y1) <= minLength) {
                 return false;
             }
 
@@ -941,7 +966,7 @@
                 MarlinUtils.logInfo("divQuad P0(" + x0 + ", " + y0 + ") P1(" + x1 + ", " + y1 + ") P2(" + x2 + ", " + y2 + ")");
             }
 
-            if (DO_CHECK_LENGTH && Helpers.fastQuadLen(x0, y0, x1, y1, x2, y2) <= LEN_TH) {
+            if (DO_CHECK_LENGTH && Helpers.fastQuadLen(x0, y0, x1, y1, x2, y2) <= minLength) {
                 return false;
             }
 
@@ -964,7 +989,7 @@
                 MarlinUtils.logInfo("divCurve P0(" + x0 + ", " + y0 + ") P1(" + x1 + ", " + y1 + ") P2(" + x2 + ", " + y2 + ") P3(" + x3 + ", " + y3 + ")");
             }
 
-            if (DO_CHECK_LENGTH && Helpers.fastCurvelen(x0, y0, x1, y1, x2, y2, x3, y3) <= LEN_TH) {
+            if (DO_CHECK_LENGTH && Helpers.fastCurvelen(x0, y0, x1, y1, x2, y2, x3, y3) <= minLength) {
                 return false;
             }
 
@@ -992,8 +1017,8 @@
                                                         outCodeOR, clipRectPad);
 
             if (TRACE) {
-                MarlinUtils.logInfo("nSplits: "+ nSplits);
-                MarlinUtils.logInfo("subTs: "+Arrays.toString(Arrays.copyOfRange(subTs, 0, nSplits)));
+                MarlinUtils.logInfo("nSplits: " + nSplits);
+                MarlinUtils.logInfo("subTs: " + Arrays.toString(Arrays.copyOfRange(subTs, 0, nSplits)));
             }
             if (nSplits == 0) {
                 // only curve support shortcut
@@ -1011,7 +1036,7 @@
 
             for (int i = 0, off = 0; i <= nSplits; i++, off += type) {
                 if (TRACE) {
-                    MarlinUtils.logInfo("Part Curve "+Arrays.toString(Arrays.copyOfRange(mid, off, off + type)));
+                    MarlinUtils.logInfo("Part Curve " + Arrays.toString(Arrays.copyOfRange(mid, off, off + type)));
                 }
                 emitCurrent(type, mid, off, out);
             }
--- a/src/java.desktop/share/classes/sun/java2d/marlin/Version.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/java.desktop/share/classes/sun/java2d/marlin/Version.java	Mon Oct 01 09:56:45 2018 +0100
@@ -27,7 +27,7 @@
 
 public final class Version {
 
-    private static final String VERSION = "marlin-0.9.1-Unsafe-OpenJDK";
+    private static final String VERSION = "marlin-0.9.1.1-Unsafe-OpenJDK";
 
     public static String getVersion() {
         return VERSION;
--- a/src/java.desktop/share/classes/sun/print/RasterPrinterJob.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/java.desktop/share/classes/sun/print/RasterPrinterJob.java	Mon Oct 01 09:56:45 2018 +0100
@@ -895,17 +895,16 @@
    }
 
     protected PageFormat getPageFormatFromAttributes() {
-        if (attributes == null || attributes.isEmpty()) {
+        Pageable pageable = null;
+        if (attributes == null || attributes.isEmpty() ||
+            !((pageable = getPageable()) instanceof OpenBook)) {
             return null;
         }
 
         PageFormat newPf = attributeToPageFormat(
             getPrintService(), attributes);
         PageFormat oldPf = null;
-        Pageable pageable = getPageable();
-        if ((pageable != null) &&
-            (pageable instanceof OpenBook) &&
-            ((oldPf = pageable.getPageFormat(0)) != null)) {
+        if ((oldPf = pageable.getPageFormat(0)) != null) {
             // If orientation, media, imageable area attributes are not in
             // "attributes" set, then use respective values of the existing
             // page format "oldPf".
--- a/src/java.desktop/share/native/libfontmanager/freetypeScaler.c	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/java.desktop/share/native/libfontmanager/freetypeScaler.c	Mon Oct 01 09:56:45 2018 +0100
@@ -679,7 +679,6 @@
     int error, imageSize;
     UInt16 width, height;
     GlyphInfo *glyphInfo;
-    int glyph_index;
     int renderFlags = FT_LOAD_RENDER, target;
     FT_GlyphSlot ftglyph;
 
@@ -720,8 +719,6 @@
     }
     renderFlags |= target;
 
-    glyph_index = FT_Get_Char_Index(scalerInfo->face, glyphCode);
-
     error = FT_Load_Glyph(scalerInfo->face, glyphCode, renderFlags);
     if (error) {
         //do not destroy scaler yet.
@@ -958,7 +955,6 @@
         FTScalerContext *context, FTScalerInfo* scalerInfo,
         jint glyphCode, jfloat xpos, jfloat ypos) {
     int renderFlags;
-    int glyph_index;
     FT_Error error;
     FT_GlyphSlot ftglyph;
 
@@ -974,8 +970,6 @@
 
     renderFlags = FT_LOAD_NO_HINTING | FT_LOAD_NO_BITMAP;
 
-    glyph_index = FT_Get_Char_Index(scalerInfo->face, glyphCode);
-
     error = FT_Load_Glyph(scalerInfo->face, glyphCode, renderFlags);
     if (error) {
         return NULL;
--- a/src/java.desktop/unix/classes/sun/awt/X11/XIconWindow.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/java.desktop/unix/classes/sun/awt/X11/XIconWindow.java	Mon Oct 01 09:56:45 2018 +0100
@@ -281,8 +281,9 @@
                 ColorData cdata = adata.get_color_data(0);
                 int num_colors = cdata.get_awt_numICMcolors();
                 for (int i = 0; i < buf.length; i++) {
-                    buf[i] = (buf[i] >= num_colors) ?
-                        0 : cdata.get_awt_icmLUT2Colors(buf[i]);
+                    int b = Byte.toUnsignedInt(buf[i]);
+                    buf[i] = (b >= num_colors) ?
+                        0 : cdata.get_awt_icmLUT2Colors(b);
                 }
                 bytes = Native.toData(buf);
             } else if (srcBuf instanceof DataBufferInt) {
--- a/src/java.desktop/unix/classes/sun/awt/X11/XToolkit.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/java.desktop/unix/classes/sun/awt/X11/XToolkit.java	Mon Oct 01 09:56:45 2018 +0100
@@ -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.
  * 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,12 @@
     static long awt_defaultFg; // Pixel
     private static XMouseInfoPeer xPeer;
 
+    /**
+     * Should we check "_NET_WM_STRUT/_NET_WM_STRUT_PARTIAL" during insets
+     * calculation.
+     */
+    private static Boolean checkSTRUT;
+
     static {
         initSecurityWarning();
         if (GraphicsEnvironment.isHeadless()) {
@@ -826,13 +832,26 @@
     }
 
     /*
-     * If we're running in non-Xinerama environment and the current
-     * window manager supports _NET protocol then the screen insets
-     * are calculated using _NET_WM_WORKAREA property of the root
-     * window.
-     * Otherwise, i. e. if Xinerama is on or _NET_WM_WORKAREA is
-     * not set, we try to calculate the insets ourselves using
-     * getScreenInsetsManually method.
+     * If the current window manager supports _NET protocol then the screen
+     * insets are calculated using _NET_WORKAREA property of the root window.
+     * <p>
+     * Note that _NET_WORKAREA is a rectangular area and it does not work
+     * well in the Xinerama mode.
+     * <p>
+     * We will trust the part of this rectangular area only if it starts at the
+     * requested graphics configuration. Below is an example when the
+     * _NET_WORKAREA intersects with the requested graphics configuration but
+     * produces wrong result.
+     *
+     *         //<-x1,y1///////
+     *         //            // ////////////////
+     *         //  SCREEN1   // // SCREEN2    //
+     *         // ********** // //     x2,y2->//
+     *         //////////////// //            //
+     *                          ////////////////
+     *
+     * When two screens overlap and the first contains a dock(*****), then
+     * _NET_WORKAREA may start at point x1,y1 and end at point x2,y2.
      */
     @Override
     public Insets getScreenInsets(GraphicsConfiguration gc)
@@ -846,30 +865,33 @@
         XToolkit.awtLock();
         try
         {
-            X11GraphicsConfig x11gc = (X11GraphicsConfig)gc;
-            X11GraphicsDevice x11gd = x11gc.getDevice();
-            long root = XlibUtil.getRootWindow(x11gd.getScreen());
+            X11GraphicsEnvironment x11ge = (X11GraphicsEnvironment)
+                    GraphicsEnvironment.getLocalGraphicsEnvironment();
+            X11GraphicsConfig x11gc = (X11GraphicsConfig) gc;
+            long root = XlibUtil.getRootWindow(x11gc.getDevice().getScreen());
             int scale = x11gc.getScale();
-            Rectangle rootBounds = XlibUtil.getWindowGeometry(root, scale);
-
-            X11GraphicsEnvironment x11ge = (X11GraphicsEnvironment)
-                GraphicsEnvironment.getLocalGraphicsEnvironment();
-            if (!x11ge.runningXinerama())
-            {
-                Insets screenInsets = getInsets(root, rootBounds, scale);
-                if (screenInsets != null) return screenInsets;
+            if (x11ge.runningXinerama() && checkSTRUT()) {
+                // implementation based on _NET_WM_STRUT/_NET_WM_STRUT_PARTIAL
+                Rectangle rootBounds = XlibUtil.getWindowGeometry(root, scale);
+                Insets insets = getScreenInsetsManually(root, rootBounds,
+                                                        gc.getBounds(), scale);
+                if ((insets.left | insets.top | insets.bottom | insets.right) != 0
+                        || rootBounds == null) {
+                    return insets;
+                }
             }
-
-            Insets insets = getScreenInsetsManually(root, rootBounds,
-                    gc.getBounds(), scale);
-            if ((insets.left | insets.top | insets.bottom | insets.right) == 0
-                    && rootBounds != null ) {
-                root = XlibWrapper.RootWindow(XToolkit.getDisplay(),
-                        x11gd.getScreen());
-                Insets screenInsets = getInsets(root, rootBounds, scale);
-                if (screenInsets != null) return screenInsets;
+            Rectangle workArea = XToolkit.getWorkArea(root, scale);
+            Rectangle screen = gc.getBounds();
+            if (workArea != null && screen.contains(workArea.getLocation())) {
+                workArea = workArea.intersection(screen);
+                int top = workArea.y - screen.y;
+                int left = workArea.x - screen.x;
+                int bottom = screen.height - workArea.height - top;
+                int right = screen.width - workArea.width - left;
+                return new Insets(top, left, bottom, right);
             }
-            return insets;
+            // Note that it is better to return zeros than inadequate values
+            return new Insets(0, 0, 0, 0);
         }
         finally
         {
@@ -877,14 +899,16 @@
         }
     }
 
-    private Insets getInsets(long root, Rectangle rootBounds, int scale) {
-        Rectangle workArea = XToolkit.getWorkArea(root, scale);
-        if (workArea == null) {
-            return null;
+    /**
+     * Returns the value of "sun.awt.X11.checkSTRUT" property. Default value is
+     * {@code false}.
+     */
+    private static boolean checkSTRUT() {
+        if (checkSTRUT == null) {
+            checkSTRUT = AccessController.doPrivileged(
+                    new GetBooleanAction("sun.awt.X11.checkSTRUT"));
         }
-        return new Insets(workArea.y, workArea.x,
-                rootBounds.height - workArea.height - workArea.y,
-                rootBounds.width - workArea.width - workArea.x);
+        return checkSTRUT;
     }
 
     /*
@@ -893,6 +917,14 @@
      * hints' values to screen insets.
      *
      * This method should be called under XToolkit.awtLock()
+     *
+     * This method is unused by default because of two reasons:
+     *  - Iteration over windows may be extremely slow, and execution of
+     *    getScreenInsets() can be x100 slower than in one monitor config.
+     *  - _NET_WM_STRUT/_NET_WM_STRUT_PARTIAL are hints for the applications.
+     *    WM should take into account these hints when "_NET_WORKAREA" is
+     *    calculated, but the system panels do not necessarily contain these
+     *    hints(Gnome 3 for example).
      */
     private Insets getScreenInsetsManually(long root, Rectangle rootBounds,
                                            Rectangle screenBounds, int scale)
--- a/src/java.desktop/unix/legal/xwindows.md	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/java.desktop/unix/legal/xwindows.md	Mon Oct 01 09:56:45 2018 +0100
@@ -125,61 +125,6 @@
 
 _____________________________
 
-Copyright notice for HPkeysym.h:
-/*
-
-Copyright 1987, 1998 The Open Group
-
-All Rights Reserved.
-
-The above copyright notice and this permission notice shall be included
-in all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
-IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR
-OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
-ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
-OTHER DEALINGS IN THE SOFTWARE.
-
-Except as contained in this notice, the name of The Open Group shall
-not be used in advertising or otherwise to promote the sale, use or
-other dealings in this Software without prior written authorization
-from The Open Group.
-
-Copyright 1987 by Digital Equipment Corporation, Maynard, Massachusetts,
-
-All Rights Reserved
-
-Permission to use, copy, modify, and distribute this software and its
-documentation for any purpose and without fee is hereby granted,
-provided that the above copyright notice appear in all copies and that
-both that copyright notice and this permission notice appear in
-supporting documentation, and that the names of Hewlett Packard
-or Digital not be
-used in advertising or publicity pertaining to distribution of the
-software without specific, written prior permission.
-
-DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
-ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
-DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
-ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
-WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
-ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
-SOFTWARE.
-
-HEWLETT-PACKARD MAKES NO WARRANTY OF ANY KIND WITH REGARD
-TO THIS SOFWARE, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
-PURPOSE. Hewlett-Packard shall not be liable for errors
-contained herein or direct, indirect, special, incidental or
-consequential damages in connection with the furnishing,
-performance, or use of this material.
-
-*/
-_____________________________________
-
 Copyright notice in keysym2ucs.h:
 
 Copyright 1987, 1994, 1998 The Open Group
--- a/src/java.desktop/unix/native/libawt_xawt/awt/HPkeysym.h	Wed Sep 26 18:11:00 2018 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,165 +0,0 @@
-/*
- * reserved comment block
- * DO NOT REMOVE OR ALTER!
- */
-/* $Xorg: HPkeysym.h,v 1.4 2000/08/18 04:05:43 coskrey Exp $ */
-/*
-
-Copyright 1987, 1998  The Open Group
-
-All Rights Reserved.
-
-The above copyright notice and this permission notice shall be included
-in all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
-IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR
-OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
-ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
-OTHER DEALINGS IN THE SOFTWARE.
-
-Except as contained in this notice, the name of The Open Group shall
-not be used in advertising or otherwise to promote the sale, use or
-other dealings in this Software without prior written authorization
-from The Open Group.
-
-Copyright 1987 by Digital Equipment Corporation, Maynard, Massachusetts,
-
-                        All Rights Reserved
-
-Permission to use, copy, modify, and distribute this software and its
-documentation for any purpose and without fee is hereby granted,
-provided that the above copyright notice appear in all copies and that
-both that copyright notice and this permission notice appear in
-supporting documentation, and that the names of Hewlett Packard
-or Digital not be
-used in advertising or publicity pertaining to distribution of the
-software without specific, written prior permission.
-
-DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
-ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
-DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
-ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
-WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
-ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
-SOFTWARE.
-
-HEWLETT-PACKARD MAKES NO WARRANTY OF ANY KIND WITH REGARD
-TO THIS SOFWARE, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
-PURPOSE.  Hewlett-Packard shall not be liable for errors
-contained herein or direct, indirect, special, incidental or
-consequential damages in connection with the furnishing,
-performance, or use of this material.
-
-*/
-
-#ifndef _HPKEYSYM_H
-
-#define _HPKEYSYM_H
-
-#define hpXK_ClearLine          0x1000FF6F
-#define hpXK_InsertLine         0x1000FF70
-#define hpXK_DeleteLine         0x1000FF71
-#define hpXK_InsertChar         0x1000FF72
-#define hpXK_DeleteChar         0x1000FF73
-#define hpXK_BackTab            0x1000FF74
-#define hpXK_KP_BackTab         0x1000FF75
-#define hpXK_Modelock1          0x1000FF48
-#define hpXK_Modelock2          0x1000FF49
-#define hpXK_Reset              0x1000FF6C
-#define hpXK_System             0x1000FF6D
-#define hpXK_User               0x1000FF6E
-#define hpXK_mute_acute         0x100000A8
-#define hpXK_mute_grave         0x100000A9
-#define hpXK_mute_asciicircum   0x100000AA
-#define hpXK_mute_diaeresis     0x100000AB
-#define hpXK_mute_asciitilde    0x100000AC
-#define hpXK_lira               0x100000AF
-#define hpXK_guilder            0x100000BE
-#define hpXK_Ydiaeresis         0x100000EE
-#define hpXK_IO                 0x100000EE
-#define hpXK_longminus          0x100000F6
-#define hpXK_block              0x100000FC
-
-
-#ifndef _OSF_Keysyms
-#define _OSF_Keysyms
-
-#define osfXK_Copy              0x1004FF02
-#define osfXK_Cut               0x1004FF03
-#define osfXK_Paste             0x1004FF04
-#define osfXK_BackTab           0x1004FF07
-#define osfXK_BackSpace         0x1004FF08
-#define osfXK_Clear             0x1004FF0B
-#define osfXK_Escape            0x1004FF1B
-#define osfXK_AddMode           0x1004FF31
-#define osfXK_PrimaryPaste      0x1004FF32
-#define osfXK_QuickPaste        0x1004FF33
-#define osfXK_PageLeft          0x1004FF40
-#define osfXK_PageUp            0x1004FF41
-#define osfXK_PageDown          0x1004FF42
-#define osfXK_PageRight         0x1004FF43
-#define osfXK_Activate          0x1004FF44
-#define osfXK_MenuBar           0x1004FF45
-#define osfXK_Left              0x1004FF51
-#define osfXK_Up                0x1004FF52
-#define osfXK_Right             0x1004FF53
-#define osfXK_Down              0x1004FF54
-#define osfXK_EndLine           0x1004FF57
-#define osfXK_BeginLine         0x1004FF58
-#define osfXK_EndData           0x1004FF59
-#define osfXK_BeginData         0x1004FF5A
-#define osfXK_PrevMenu          0x1004FF5B
-#define osfXK_NextMenu          0x1004FF5C
-#define osfXK_PrevField         0x1004FF5D
-#define osfXK_NextField         0x1004FF5E
-#define osfXK_Select            0x1004FF60
-#define osfXK_Insert            0x1004FF63
-#define osfXK_Undo              0x1004FF65
-#define osfXK_Menu              0x1004FF67
-#define osfXK_Cancel            0x1004FF69
-#define osfXK_Help              0x1004FF6A
-#define osfXK_SelectAll         0x1004FF71
-#define osfXK_DeselectAll       0x1004FF72
-#define osfXK_Reselect          0x1004FF73
-#define osfXK_Extend            0x1004FF74
-#define osfXK_Restore           0x1004FF78
-#define osfXK_Delete            0x1004FFFF
-
-#endif /* _OSF_Keysyms */
-
-
-/**************************************************************
- * The use of the following macros is deprecated.
- * They are listed below only for backwards compatibility.
- */
-#define XK_Reset                0x1000FF6C
-#define XK_System               0x1000FF6D
-#define XK_User                 0x1000FF6E
-#define XK_ClearLine            0x1000FF6F
-#define XK_InsertLine           0x1000FF70
-#define XK_DeleteLine           0x1000FF71
-#define XK_InsertChar           0x1000FF72
-#define XK_DeleteChar           0x1000FF73
-#define XK_BackTab              0x1000FF74
-#define XK_KP_BackTab           0x1000FF75
-#define XK_Ext16bit_L           0x1000FF76
-#define XK_Ext16bit_R           0x1000FF77
-#define XK_mute_acute           0x100000a8
-#define XK_mute_grave           0x100000a9
-#define XK_mute_asciicircum     0x100000aa
-#define XK_mute_diaeresis       0x100000ab
-#define XK_mute_asciitilde      0x100000ac
-#define XK_lira                 0x100000af
-#define XK_guilder              0x100000be
-#ifndef XK_Ydiaeresis
-#define XK_Ydiaeresis           0x100000ee
-#endif
-#define XK_IO                   0x100000ee
-#define XK_longminus            0x100000f6
-#define XK_block                0x100000fc
-
-#endif /* _HPKEYSYM_H */
--- a/src/java.desktop/unix/native/libawt_xawt/xawt/XWindow.c	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/java.desktop/unix/native/libawt_xawt/xawt/XWindow.c	Mon Oct 01 09:56:45 2018 +0100
@@ -54,17 +54,12 @@
 #include <X11/Sunkeysym.h>  /* Sun vendor-specific */
 #include <X11/ap_keysym.h>  /* Apollo (HP) vendor-specific */
 /*
- * #include <X11/HPkeysym.h>    HP vendor-specific
- * I checked HPkeysym.h into the workspace because although
- * I think it will ship with X11R6.4.2 (and later) on Linux,
- * it doesn't seem to be in Solaris 9 Update 2.
- *
- * This is done not only for the hp keysyms, but also to
+ * HPKeysym.h is used not only for the hp keysyms, but also to
  * give us the osf keysyms that are also defined in HPkeysym.h.
  * However, HPkeysym.h is missing a couple of osf keysyms,
  * so I have #defined them below.
  */
-#include "HPkeysym.h"   /* HP vendor-specific */
+#include <X11/HPkeysym.h>   /* HP vendor-specific */
 
 #include "java_awt_event_KeyEvent.h"
 #include "java_awt_event_InputEvent.h"
--- a/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Flags.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Flags.java	Mon Oct 01 09:56:45 2018 +0100
@@ -433,7 +433,9 @@
         SYSTEM_MODULE(Flags.SYSTEM_MODULE),
         DEPRECATED_ANNOTATION(Flags.DEPRECATED_ANNOTATION),
         DEPRECATED_REMOVAL(Flags.DEPRECATED_REMOVAL),
-        HAS_RESOURCE(Flags.HAS_RESOURCE);
+        HAS_RESOURCE(Flags.HAS_RESOURCE),
+        POTENTIALLY_AMBIGUOUS(Flags.POTENTIALLY_AMBIGUOUS),
+        ANONCONSTR_BASED(Flags.ANONCONSTR_BASED);
 
         Flag(long flag) {
             this.value = flag;
--- a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Analyzer.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Analyzer.java	Mon Oct 01 09:56:45 2018 +0100
@@ -166,10 +166,10 @@
                 res = EnumSet.allOf(AnalyzerMode.class);
             }
             for (AnalyzerMode mode : values()) {
-                if (modes.contains(mode.opt)) {
+                if (modes.contains("-" + mode.opt) || !mode.feature.allowedInSource(source)) {
+                    res.remove(mode);
+                } else if (modes.contains(mode.opt)) {
                     res.add(mode);
-                } else if (modes.contains("-" + mode.opt) || !mode.feature.allowedInSource(source)) {
-                    res.remove(mode);
                 }
             }
             return res;
--- a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Attr.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Attr.java	Mon Oct 01 09:56:45 2018 +0100
@@ -2689,12 +2689,14 @@
      */
     @Override
     public void visitLambda(final JCLambda that) {
+        boolean wrongContext = false;
         if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) {
             if (pt().hasTag(NONE) && (env.info.enclVar == null || !env.info.enclVar.type.isErroneous())) {
                 //lambda only allowed in assignment or method invocation/cast context
                 log.error(that.pos(), Errors.UnexpectedLambda);
             }
             resultInfo = recoveryInfo;
+            wrongContext = true;
         }
         //create an environment for attribution of the lambda expression
         final Env<AttrContext> localEnv = lambdaEnv(that, env);
@@ -2811,7 +2813,8 @@
 
                 checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), lambdaType, currentTarget);
             }
-            result = check(that, currentTarget, KindSelector.VAL, resultInfo);
+            result = wrongContext ? that.type = types.createErrorType(pt())
+                                  : check(that, currentTarget, KindSelector.VAL, resultInfo);
         } catch (Types.FunctionDescriptorLookupError ex) {
             JCDiagnostic cause = ex.getDiagnostic();
             resultInfo.checkContext.report(that, cause);
@@ -5343,23 +5346,12 @@
         }
 
         @Override
-        public void visitLambda(JCLambda that) {
-            super.visitLambda(that);
-            if (that.target == null) {
-                that.target = syms.unknownType;
-            }
-        }
-
-        @Override
         public void visitReference(JCMemberReference that) {
             super.visitReference(that);
             if (that.sym == null) {
                 that.sym = new MethodSymbol(0, names.empty, dummyMethodType(),
                         syms.noSymbol);
             }
-            if (that.target == null) {
-                that.target = syms.unknownType;
-            }
         }
     }
     // </editor-fold>
--- a/src/jdk.compiler/share/classes/com/sun/tools/javac/launcher/Main.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/launcher/Main.java	Mon Oct 01 09:56:45 2018 +0100
@@ -50,6 +50,9 @@
 import java.nio.file.InvalidPathException;
 import java.nio.file.Path;
 import java.nio.file.Paths;
+import java.security.CodeSigner;
+import java.security.CodeSource;
+import java.security.ProtectionDomain;
 import java.text.MessageFormat;
 import java.util.ArrayList;
 import java.util.Arrays;
@@ -182,7 +185,7 @@
     public void run(String[] runtimeArgs, String[] args) throws Fault, InvocationTargetException {
         Path file = getFile(args);
 
-        Context context = new Context();
+        Context context = new Context(file.toAbsolutePath());
         String mainClassName = compile(file, getJavacOpts(runtimeArgs), context);
 
         String[] appArgs = Arrays.copyOfRange(args, 1, args.length);
@@ -193,7 +196,7 @@
      * Returns the path for the filename found in the first of an array of arguments.
      *
      * @param args the array
-     * @return the path
+     * @return the path, as given in the array of args
      * @throws Fault if there is a problem determining the path, or if the file does not exist
      */
     private Path getFile(String[] args) throws Fault {
@@ -396,6 +399,7 @@
      */
     private void execute(String mainClassName, String[] appArgs, Context context)
             throws Fault, InvocationTargetException {
+        System.setProperty("jdk.launcher.sourcefile", context.file.toString());
         ClassLoader cl = context.getClassLoader(ClassLoader.getSystemClassLoader());
         try {
             Class<?> appClass = Class.forName(mainClassName, true, cl);
@@ -478,14 +482,19 @@
      * a class loader.
      */
     private static class Context {
-        private Map<String, byte[]> inMemoryClasses = new HashMap<>();
+        private final Path file;
+        private final Map<String, byte[]> inMemoryClasses = new HashMap<>();
+
+        Context(Path file) {
+            this.file = file;
+        }
 
         JavaFileManager getFileManager(StandardJavaFileManager delegate) {
             return new MemoryFileManager(inMemoryClasses, delegate);
         }
 
         ClassLoader getClassLoader(ClassLoader parent) {
-            return new MemoryClassLoader(inMemoryClasses, parent);
+            return new MemoryClassLoader(inMemoryClasses, parent, file);
         }
     }
 
@@ -546,9 +555,22 @@
          */
         private final Map<String, byte[]> sourceFileClasses;
 
-        MemoryClassLoader(Map<String, byte[]> sourceFileClasses, ClassLoader parent) {
+        /**
+         * A minimal protection domain, specifying a code source of the source file itself,
+         * used for classes found in the source file and defined by this loader.
+         */
+        private final ProtectionDomain domain;
+
+        MemoryClassLoader(Map<String, byte[]> sourceFileClasses, ClassLoader parent, Path file) {
             super(parent);
             this.sourceFileClasses = sourceFileClasses;
+            CodeSource codeSource;
+            try {
+                codeSource = new CodeSource(file.toUri().toURL(), (CodeSigner[]) null);
+            } catch (MalformedURLException e) {
+                codeSource = null;
+            }
+            domain = new ProtectionDomain(codeSource, null, this, null);
         }
 
         /**
@@ -632,7 +654,7 @@
             if (bytes == null) {
                 throw new ClassNotFoundException(name);
             }
-            return defineClass(name, bytes, 0, bytes.length);
+            return defineClass(name, bytes, 0, bytes.length, domain);
         }
 
         @Override
--- a/src/jdk.compiler/share/classes/com/sun/tools/javac/main/Option.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/main/Option.java	Mon Oct 01 09:56:45 2018 +0100
@@ -328,7 +328,7 @@
 
     ENCODING("-encoding", "opt.arg.encoding", "opt.encoding", STANDARD, FILEMANAGER),
 
-    SOURCE("-source", "opt.arg.release", "opt.source", STANDARD, BASIC) {
+    SOURCE("--source -source", "opt.arg.release", "opt.source", STANDARD, BASIC) {
         @Override
         public void process(OptionHelper helper, String option, String operand) throws InvalidValueException {
             Source source = Source.lookup(operand);
@@ -349,7 +349,7 @@
         }
     },
 
-    TARGET("-target", "opt.arg.release", "opt.target", STANDARD, BASIC) {
+    TARGET("--target -target", "opt.arg.release", "opt.target", STANDARD, BASIC) {
         @Override
         public void process(OptionHelper helper, String option, String operand) throws InvalidValueException {
             Target target = Target.lookup(operand);
--- a/src/jdk.javadoc/share/classes/com/sun/tools/javadoc/main/Start.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/jdk.javadoc/share/classes/com/sun/tools/javadoc/main/Start.java	Mon Oct 01 09:56:45 2018 +0100
@@ -380,8 +380,8 @@
         String platformString = compOpts.get("--release");
 
         if (platformString != null) {
-            if (compOpts.isSet("-source")) {
-                usageError("main.release.bootclasspath.conflict", "-source");
+            if (compOpts.isSet(Option.SOURCE.primaryName)) {
+                usageError("main.release.bootclasspath.conflict", Option.SOURCE.primaryName);
             }
             if (fileManagerOpts.containsKey(Option.BOOT_CLASS_PATH)) {
                 usageError("main.release.bootclasspath.conflict", Option.BOOT_CLASS_PATH.getPrimaryName());
--- a/src/jdk.javadoc/share/classes/com/sun/tools/javadoc/main/ToolOption.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/jdk.javadoc/share/classes/com/sun/tools/javadoc/main/ToolOption.java	Mon Oct 01 09:56:45 2018 +0100
@@ -174,6 +174,13 @@
     SOURCE("-source", true) {
         @Override
         public void process(Helper helper, String arg) {
+            helper.setCompilerOpt("--source", arg);
+        }
+    },
+
+    SOURCE2("--source", true) {
+        @Override
+        public void process(Helper helper, String arg) {
             helper.setCompilerOpt(opt, arg);
         }
     },
--- a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/tool/ToolOption.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/tool/ToolOption.java	Mon Oct 01 09:56:45 2018 +0100
@@ -146,7 +146,7 @@
         }
     },
 
-    SOURCE("-source", STANDARD, true) {
+    SOURCE("--source -source", STANDARD, true) {
         @Override
         public void process(Helper helper, String arg) throws InvalidValueException {
             Option.SOURCE.process(helper.getOptionHelper(), primaryName, arg);
--- a/src/jdk.jdi/share/classes/com/sun/jdi/connect/ListeningConnector.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/jdk.jdi/share/classes/com/sun/jdi/connect/ListeningConnector.java	Mon Oct 01 09:56:45 2018 +0100
@@ -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,8 +44,8 @@
      * {@link #startListening} may allow
      * multiple target VM to become connected.
      *
-     * @return <code>true</code> if multiple connections are supported;
-     * <code>false</code> otherwise.
+     * @return {@code true} if multiple connections are supported;
+     * {@code false} otherwise.
      */
     boolean supportsMultipleConnections();
 
@@ -70,7 +70,7 @@
      * {@link #accept} (using the same argument map as is passed to this
      * method).
      * <p>
-     * If <code>arguments</code> contains addressing information. and
+     * If {@code arguments} contains addressing information and
      * only one connection will be accepted, the {@link #accept accept} method
      * can be called immediately without calling this method.
      *
--- a/src/jdk.jdi/share/classes/com/sun/tools/jdi/GenericListeningConnector.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/jdk.jdi/share/classes/com/sun/tools/jdi/GenericListeningConnector.java	Mon Oct 01 09:56:45 2018 +0100
@@ -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
@@ -113,8 +113,8 @@
            throw new IllegalConnectorArgumentsException("Already listening",
                new ArrayList<>(args.keySet()));
         }
-
         listener = transportService.startListening(address);
+        updateArgumentMapIfRequired(args, listener);
         listenMap.put(args, listener);
         return listener.address();
     }
@@ -183,4 +183,9 @@
     public Transport transport() {
         return transport;
     }
+
+    protected void updateArgumentMapIfRequired(
+        Map<String, ? extends Connector.Argument> args, TransportService.ListenKey listener) {
+    }
+
 }
--- a/src/jdk.jdi/share/classes/com/sun/tools/jdi/SocketListeningConnector.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/jdk.jdi/share/classes/com/sun/tools/jdi/SocketListeningConnector.java	Mon Oct 01 09:56:45 2018 +0100
@@ -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
@@ -30,6 +30,7 @@
 import com.sun.jdi.connect.Connector;
 import com.sun.jdi.connect.IllegalConnectorArgumentsException;
 import com.sun.jdi.connect.Transport;
+import com.sun.jdi.connect.spi.TransportService;
 
 /*
  * A ListeningConnector that uses the SocketTransportService
@@ -92,4 +93,21 @@
     public String description() {
         return getString("socket_listening.description");
     }
+
+    // If the port is auto detected update the argument map with the bound port number.
+    @Override
+    protected void updateArgumentMapIfRequired(
+        Map<String, ? extends Connector.Argument> args, TransportService.ListenKey listener) {
+        if (isWildcardPort(args)) {
+            String[] address = listener.address().split(":");
+            if (address.length > 1) {
+                args.get(ARG_PORT).setValue(address[1]);
+            }
+        }
+    }
+
+    private boolean isWildcardPort(Map<String, ? extends Connector.Argument> args) {
+        String port = args.get(ARG_PORT).value();
+        return port.isEmpty() || Integer.valueOf(port) == 0;
+    }
 }
--- a/src/jdk.unsupported/share/classes/sun/reflect/ReflectionFactory.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/src/jdk.unsupported/share/classes/sun/reflect/ReflectionFactory.java	Mon Oct 01 09:56:45 2018 +0100
@@ -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
@@ -29,14 +29,9 @@
 import java.lang.invoke.MethodHandle;
 import java.lang.reflect.Constructor;
 import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.UndeclaredThrowableException;
-import java.security.AccessControlContext;
 import java.security.AccessController;
 import java.security.Permission;
-import java.security.ProtectionDomain;
 import java.security.PrivilegedAction;
-import jdk.internal.misc.SharedSecrets;
-import jdk.internal.misc.JavaSecurityAccess;
 
 /**
  * ReflectionFactory supports custom serialization.
@@ -145,66 +140,6 @@
     }
 
     /**
-     * Invokes the supplied constructor, adding the provided protection domains
-     * to the invocation stack before invoking {@code Constructor::newInstance}.
-     * If no {@linkplain System#getSecurityManager() security manager} is present,
-     * or no domains are provided, then this method simply calls
-     * {@code cons.newInstance()}. Otherwise, it invokes the provided constructor
-     * with privileges at the intersection of the current context and the provided
-     * protection domains.
-     *
-     * @param cons A constructor obtained from {@code
-     *        newConstructorForSerialization} or {@code
-     *        newConstructorForExternalization}.
-     * @param domains An array of protection domains that limit the privileges
-     *        with which the constructor is invoked. Can be {@code null}
-     *        or empty, in which case privileges are only limited by the
-     *        {@linkplain AccessController#getContext() current context}.
-     *
-     * @return A new object built from the provided constructor.
-     *
-     * @throws NullPointerException if {@code cons} is {@code null}.
-     * @throws InstantiationException if thrown by {@code cons.newInstance()}.
-     * @throws InvocationTargetException if thrown by {@code cons.newInstance()}.
-     * @throws IllegalAccessException if thrown by {@code cons.newInstance()}.
-     */
-    public final Object newInstanceForSerialization(Constructor<?> cons,
-                                                    ProtectionDomain[] domains)
-        throws InstantiationException, InvocationTargetException, IllegalAccessException
-    {
-        SecurityManager sm = System.getSecurityManager();
-        if (sm == null || domains == null || domains.length == 0) {
-            return cons.newInstance();
-        } else {
-            JavaSecurityAccess jsa = SharedSecrets.getJavaSecurityAccess();
-            PrivilegedAction<?> pea = () -> {
-                try {
-                    return cons.newInstance();
-                } catch (InstantiationException
-                         | InvocationTargetException
-                         | IllegalAccessException x) {
-                    throw new UndeclaredThrowableException(x);
-                }
-            }; // Can't use PrivilegedExceptionAction with jsa
-            try {
-                return jsa.doIntersectionPrivilege(pea,
-                           AccessController.getContext(),
-                           new AccessControlContext(domains));
-            } catch (UndeclaredThrowableException x) {
-                Throwable cause = x.getCause();
-                 if (cause instanceof InstantiationException)
-                    throw (InstantiationException) cause;
-                if (cause instanceof InvocationTargetException)
-                    throw (InvocationTargetException) cause;
-                if (cause instanceof IllegalAccessException)
-                    throw (IllegalAccessException) cause;
-                // not supposed to happen
-                throw x;
-            }
-        }
-    }
-
-    /**
      * Returns a direct MethodHandle for the {@code readObjectNoData} method on
      * a Serializable class.
      * The first argument of {@link MethodHandle#invoke} is the serializable
--- a/test/hotspot/gtest/code/test_dependencyContext.cpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/test/hotspot/gtest/code/test_dependencyContext.cpp	Mon Oct 01 09:56:45 2018 +0100
@@ -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
@@ -50,7 +50,7 @@
   }
 
   ~TestDependencyContext() {
-    dependencies().wipe();
+    wipe();
     CodeCache_lock->unlock();
   }
 
@@ -63,6 +63,18 @@
     return ctx.find_stale_entries();
   }
 #endif
+
+  void wipe() {
+    DependencyContext ctx(&_dependency_context);
+    nmethodBucket* b = ctx.dependencies();
+    ctx.set_dependencies(NULL);
+    ctx.set_has_stale_entries(false);
+    while (b != NULL) {
+      nmethodBucket* next = b->next();
+      delete b;
+      b = next;
+    }
+  }
 };
 
 static void test_remove_dependent_nmethod(int id, bool delete_immediately) {
--- a/test/hotspot/jtreg/ProblemList-graal.txt	Wed Sep 26 18:11:00 2018 +0100
+++ b/test/hotspot/jtreg/ProblemList-graal.txt	Mon Oct 01 09:56:45 2018 +0100
@@ -175,7 +175,7 @@
 org.graalvm.compiler.replacements.test.classfile.RedefineIntrinsicTest           8205081
 
 org.graalvm.compiler.core.test.deopt.CompiledMethodTest          8202955
-org.graalvm.compiler.core.test.CountedLoopTest                   8199885
+org.graalvm.compiler.core.test.CountedLoopTest                   8211179
 org.graalvm.compiler.debug.test.DebugContextTest                 8203504
 
 org.graalvm.compiler.hotspot.test.GraalOSRTest                   8206947
--- a/test/hotspot/jtreg/compiler/graalunit/CoreTest.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/test/hotspot/jtreg/compiler/graalunit/CoreTest.java	Mon Oct 01 09:56:45 2018 +0100
@@ -25,7 +25,7 @@
  * @test
  * @summary
  * @requires vm.opt.final.EnableJVMCI == true
- *
+ * @requires !vm.graal.enabled
  * @modules jdk.internal.vm.compiler
  *
  * @library /test/lib /compiler/graalunit /
--- a/test/hotspot/jtreg/compiler/graalunit/TestPackages.txt	Wed Sep 26 18:11:00 2018 +0100
+++ b/test/hotspot/jtreg/compiler/graalunit/TestPackages.txt	Mon Oct 01 09:56:45 2018 +0100
@@ -6,7 +6,7 @@
 AsmSparc      org.graalvm.compiler.asm.sparc.test
 CoreAmd64     org.graalvm.compiler.core.amd64.test
 CoreSparc     org.graalvm.compiler.core.sparc.test @requires vm.simpleArch == "sparcv9"
-Core          org.graalvm.compiler.core.test
+Core          org.graalvm.compiler.core.test       @requires !vm.graal.enabled
 Debug         org.graalvm.compiler.debug.test
 Graph         org.graalvm.compiler.graph.test      @requires vm.graal.enabled
 HotspotAmd64  org.graalvm.compiler.hotspot.amd64.test
--- a/test/hotspot/jtreg/gc/TestAllocateHeapAt.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/test/hotspot/jtreg/gc/TestAllocateHeapAt.java	Mon Oct 01 09:56:45 2018 +0100
@@ -24,7 +24,7 @@
 /* @test TestAllocateHeapAt.java
  * @key gc
  * @summary Test to check allocation of Java Heap with AllocateHeapAt option
- * @requires vm.gc != "Z"
+ * @requires vm.gc != "Z" & os.family != "aix"
  * @library /test/lib
  * @modules java.base/jdk.internal.misc
  */
--- a/test/hotspot/jtreg/gc/TestAllocateHeapAtError.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/test/hotspot/jtreg/gc/TestAllocateHeapAtError.java	Mon Oct 01 09:56:45 2018 +0100
@@ -24,7 +24,7 @@
 /* @test TestAllocateHeapAtError.java
  * @key gc
  * @summary Test to check correct handling of non-existent directory passed to AllocateHeapAt option
- * @requires vm.gc != "Z"
+ * @requires vm.gc != "Z" & os.family != "aix"
  * @library /test/lib
  * @modules java.base/jdk.internal.misc
  */
--- a/test/hotspot/jtreg/gc/TestAllocateHeapAtMultiple.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/test/hotspot/jtreg/gc/TestAllocateHeapAtMultiple.java	Mon Oct 01 09:56:45 2018 +0100
@@ -26,7 +26,7 @@
  * @summary Test to check allocation of Java Heap with AllocateHeapAt option. Has multiple sub-tests to cover different code paths.
  * @library /test/lib
  * @modules java.base/jdk.internal.misc
- * @requires vm.bits == "64" & vm.gc != "Z"
+ * @requires vm.bits == "64" & vm.gc != "Z" & os.family != "aix"
  */
 
 import jdk.test.lib.JDKToolFinder;
--- a/test/hotspot/jtreg/gc/stress/gcbasher/TestGCBasherWithAllocateHeapAt.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/test/hotspot/jtreg/gc/stress/gcbasher/TestGCBasherWithAllocateHeapAt.java	Mon Oct 01 09:56:45 2018 +0100
@@ -28,7 +28,7 @@
  * @test TestGCBasherWithAllocateHeapAt
  * @key gc stress
  * @requires vm.gc.G1
- * @requires vm.flavor == "server" & !vm.emulatedClient
+ * @requires vm.flavor == "server" & !vm.emulatedClient & os.family != "aix"
  * @summary Stress Java heap allocation with AllocateHeapAt flag using GC basher.
  * @run main/othervm/timeout=500 -Xlog:gc*=info -Xmx256m -server -XX:+UseG1GC -XX:AllocateHeapAt=. TestGCBasherWithAllocateHeapAt 120000
  */
--- a/test/hotspot/jtreg/runtime/CommandLine/VMDeprecatedOptions.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/test/hotspot/jtreg/runtime/CommandLine/VMDeprecatedOptions.java	Mon Oct 01 09:56:45 2018 +0100
@@ -46,6 +46,7 @@
         {"InitialRAMFraction",        "64"},
         {"AssumeMP",                  "false"},
         {"UseMembar",                 "true"},
+        {"TLABStats",                 "false"},
 
         // deprecated alias flags (see also aliased_jvm_flags):
         {"DefaultMaxRAMFraction", "4"},
--- a/test/hotspot/jtreg/runtime/appcds/GraalWithLimitedMetaspace.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/test/hotspot/jtreg/runtime/appcds/GraalWithLimitedMetaspace.java	Mon Oct 01 09:56:45 2018 +0100
@@ -87,7 +87,6 @@
 
     static void dumpLoadedClasses(String[] expectedClasses) throws Exception {
         ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(true,
-          TestCommon.makeCommandLineForAppCDS(
             "-XX:DumpLoadedClassList=" + CLASSLIST_FILE,
             // trigger JVMCI runtime init so that JVMCI classes will be
             // included in the classlist
@@ -95,7 +94,7 @@
             "-cp",
             TESTJAR,
             TESTNAME,
-            TEST_OUT));
+            TEST_OUT);
 
         OutputAnalyzer output = TestCommon.executeAndLog(pb, "dump-loaded-classes")
             .shouldHaveExitValue(0)
@@ -113,7 +112,6 @@
 
     static void dumpArchive() throws Exception {
         ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(true,
-          TestCommon.makeCommandLineForAppCDS(
             "-cp",
             TESTJAR,
             "-XX:SharedClassListFile=" + CLASSLIST_FILE,
@@ -121,7 +119,7 @@
             "-Xlog:cds",
             "-Xshare:dump",
             "-XX:MetaspaceSize=12M",
-            "-XX:MaxMetaspaceSize=12M"));
+            "-XX:MaxMetaspaceSize=12M");
 
         OutputAnalyzer output = TestCommon.executeAndLog(pb, "dump-archive");
         int exitValue = output.getExitValue();
--- a/test/hotspot/jtreg/runtime/appcds/TestCommon.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/test/hotspot/jtreg/runtime/appcds/TestCommon.java	Mon Oct 01 09:56:45 2018 +0100
@@ -110,10 +110,6 @@
         return createArchive(opts);
     }
 
-    public static String[] makeCommandLineForAppCDS(String... args) throws Exception {
-        return args;
-    }
-
     // Create AppCDS archive using appcds options
     public static OutputAnalyzer createArchive(AppCDSOptions opts)
         throws Exception {
@@ -143,7 +139,7 @@
         for (String s : opts.suffix) cmd.add(s);
 
         String[] cmdLine = cmd.toArray(new String[cmd.size()]);
-        ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(true, makeCommandLineForAppCDS(cmdLine));
+        ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(true, cmdLine);
         return executeAndLog(pb, "dump");
     }
 
@@ -169,7 +165,7 @@
         for (String s : opts.suffix) cmd.add(s);
 
         String[] cmdLine = cmd.toArray(new String[cmd.size()]);
-        ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(true, makeCommandLineForAppCDS(cmdLine));
+        ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(true, cmdLine);
         return executeAndLog(pb, "exec");
     }
 
--- a/test/hotspot/jtreg/runtime/appcds/sharedStrings/SharedStringsBasic.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/test/hotspot/jtreg/runtime/appcds/sharedStrings/SharedStringsBasic.java	Mon Oct 01 09:56:45 2018 +0100
@@ -49,24 +49,22 @@
             TestCommon.getSourceFile("SharedStringsBasic.txt").toString();
 
         ProcessBuilder dumpPb = ProcessTools.createJavaProcessBuilder(true,
-          TestCommon.makeCommandLineForAppCDS(
             "-cp", appJar,
             "-XX:SharedArchiveConfigFile=" + sharedArchiveConfigFile,
             "-XX:SharedArchiveFile=./SharedStringsBasic.jsa",
             "-Xshare:dump",
-            "-Xlog:cds,cds+hashtables"));
+            "-Xlog:cds,cds+hashtables");
 
         TestCommon.executeAndLog(dumpPb, "dump")
             .shouldContain("Shared string table stats")
             .shouldHaveExitValue(0);
 
         ProcessBuilder runPb = ProcessTools.createJavaProcessBuilder(true,
-          TestCommon.makeCommandLineForAppCDS(
             "-cp", appJar,
             "-XX:SharedArchiveFile=./SharedStringsBasic.jsa",
             "-Xshare:auto",
             "-showversion",
-            "HelloString"));
+            "HelloString");
 
         TestCommon.executeAndLog(runPb, "run").shouldHaveExitValue(0);
     }
--- a/test/hotspot/jtreg/runtime/appcds/sharedStrings/SysDictCrash.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/test/hotspot/jtreg/runtime/appcds/sharedStrings/SysDictCrash.java	Mon Oct 01 09:56:45 2018 +0100
@@ -44,21 +44,19 @@
         // SharedBaseAddress=0 puts the archive at a very high address on solaris,
         // which provokes the crash.
         ProcessBuilder dumpPb = ProcessTools.createJavaProcessBuilder(true,
-          TestCommon.makeCommandLineForAppCDS(
             "-XX:+UseG1GC", "-XX:MaxRAMPercentage=12.5",
             "-cp", ".",
             "-XX:SharedBaseAddress=0", "-XX:SharedArchiveFile=./SysDictCrash.jsa",
             "-Xshare:dump",
-            "-showversion", "-Xlog:cds,cds+hashtables"));
+            "-showversion", "-Xlog:cds,cds+hashtables");
 
         TestCommon.checkDump(TestCommon.executeAndLog(dumpPb, "dump"));
 
         ProcessBuilder runPb = ProcessTools.createJavaProcessBuilder(true,
-          TestCommon.makeCommandLineForAppCDS(
             "-XX:+UseG1GC", "-XX:MaxRAMPercentage=12.5",
             "-XX:SharedArchiveFile=./SysDictCrash.jsa",
             "-Xshare:on",
-            "-version"));
+            "-version");
 
         TestCommon.checkExec(TestCommon.executeAndLog(runPb, "exec"));
     }
--- a/test/hotspot/jtreg/serviceability/sa/ClhsdbCDSCore.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/test/hotspot/jtreg/serviceability/sa/ClhsdbCDSCore.java	Mon Oct 01 09:56:45 2018 +0100
@@ -79,6 +79,7 @@
             CDSTestUtils.createArchiveAndCheck(opts);
 
             String[] jArgs = {
+                "-Xmx512m",
                 "-XX:+UnlockDiagnosticVMOptions",
                 "-XX:SharedArchiveFile=" + SHARED_ARCHIVE_NAME,
                 "-XX:+CreateCoredumpOnCrash",
--- a/test/hotspot/jtreg/serviceability/sa/TestHeapDumpForInvokeDynamic.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/test/hotspot/jtreg/serviceability/sa/TestHeapDumpForInvokeDynamic.java	Mon Oct 01 09:56:45 2018 +0100
@@ -123,6 +123,7 @@
         try {
             List<String> vmArgs = new ArrayList<String>();
             vmArgs.add("-XX:+UsePerfData");
+            vmArgs.add("-Xmx512m");
             vmArgs.addAll(Utils.getVmOptions());
 
             theApp = new LingeredAppWithInvokeDynamic();
--- a/test/hotspot/jtreg/serviceability/sa/TestJmapCore.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/test/hotspot/jtreg/serviceability/sa/TestJmapCore.java	Mon Oct 01 09:56:45 2018 +0100
@@ -87,7 +87,7 @@
 
     static void test(String type) throws Throwable {
         ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(true, "-XX:+CreateCoredumpOnCrash",
-                "-XX:MaxMetaspaceSize=64m", "-XX:+CrashOnOutOfMemoryError",
+                "-Xmx512m", "-XX:MaxMetaspaceSize=64m", "-XX:+CrashOnOutOfMemoryError",
                 TestJmapCore.class.getName(), type);
 
         boolean useDefaultUlimit = useDefaultUlimit();
--- a/test/hotspot/jtreg/vmTestbase/nsk/jdb/exclude/exclude001/exclude001.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/test/hotspot/jtreg/vmTestbase/nsk/jdb/exclude/exclude001/exclude001.java	Mon Oct 01 09:56:45 2018 +0100
@@ -61,9 +61,9 @@
  * @run driver jdk.test.lib.FileInstaller . .
  * @build nsk.jdb.exclude.exclude001.exclude001
  *        nsk.jdb.exclude.exclude001.exclude001a
- * @run main/othervm/timeout=420 PropertyResolvingWrapper nsk.jdb.exclude.exclude001.exclude001
+ * @run main/othervm/timeout=600 PropertyResolvingWrapper nsk.jdb.exclude.exclude001.exclude001
  *      -arch=${os.family}-${os.simpleArch}
- *      -waittime=7
+ *      -waittime=10
  *      -debugee.vmkind=java
  *      -transport.address=dynamic
  *      -jdb=${test.jdk}/bin/jdb
@@ -129,7 +129,7 @@
             oldExclude = reply[0];
 
             for (int testCase = 0; testCase < exclude001a.numThreads; testCase++) {
-
+                String expectedPrompt = MYTHREAD + "-" + testCase + "[1]";
                 reply = jdb.receiveReplyFor(JdbCommand.cont);
 
                 if (jdb.isAtBreakpoint(reply, LAST_BREAK)) {
@@ -153,14 +153,14 @@
                                 reply = jdb.receiveReplyFor(JdbCommand.exclude + "javax.*,sun.*,com.sun.*,jdk.*");
                                 break;
                         case 2: // allow sun.*
-                                reply = jdb.receiveReplyFor(JdbCommand.exclude + "java.*,javax.*,com.sun.*,jdk.");
+                                reply = jdb.receiveReplyFor(JdbCommand.exclude + "java.*,javax.*,com.sun.*,jdk.*");
                                 break;
                         }
 
                         reply = jdb.receiveReplyFor(JdbCommand.trace + "methods " + threads[0]);
 
                         while (true) {
-                            reply = jdb.receiveReplyFor(JdbCommand.cont);
+                            reply = jdb.receiveReplyForWithMessageWait(JdbCommand.cont, expectedPrompt);
 
                             grep = new Paragrep(reply);
                             count = grep.find(JAVA_CORE_METHOD);
--- a/test/hotspot/jtreg/vmTestbase/nsk/jvmti/scenarios/hotswap/HS203/hs203t003/hs203t003.cpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/test/hotspot/jtreg/vmTestbase/nsk/jvmti/scenarios/hotswap/HS203/hs203t003/hs203t003.cpp	Mon Oct 01 09:56:45 2018 +0100
@@ -174,6 +174,23 @@
     return JNI_OK;
 }
 
+JNIEXPORT jboolean JNICALL
+Java_nsk_jvmti_scenarios_hotswap_HS203_hs203t003_hs203t003_isSuspended(JNIEnv * jni,
+        jclass clas,
+        jthread thread) {
+    jboolean retvalue;
+    jint state;
+    retvalue = JNI_FALSE;
+    if ( ! NSK_JVMTI_VERIFY( NSK_CPP_STUB3(GetThreadState, jvmti, thread, &state) )  ) {
+        nsk_printf(" Agent :: Error while getting thread state.\n");
+        nsk_jvmti_agentFailed();
+    } else {
+        if ( state & JVMTI_THREAD_STATE_SUSPENDED) {
+          retvalue = JNI_TRUE;
+        }
+    }
+    return retvalue;
+}
 
 JNIEXPORT jboolean JNICALL
 Java_nsk_jvmti_scenarios_hotswap_HS203_hs203t003_hs203t003_popThreadFrame(JNIEnv * jni,
--- a/test/hotspot/jtreg/vmTestbase/nsk/jvmti/scenarios/hotswap/HS203/hs203t003/hs203t003.java	Wed Sep 26 18:11:00 2018 +0100
+++ b/test/hotspot/jtreg/vmTestbase/nsk/jvmti/scenarios/hotswap/HS203/hs203t003/hs203t003.java	Mon Oct 01 09:56:45 2018 +0100
@@ -62,7 +62,8 @@
 public class hs203t003 extends RedefineAgent {
 
     public native boolean popThreadFrame(Thread thread);
-        public native boolean resumeThread(Thread thread);
+    public native boolean isSuspended(Thread thread);
+    public native boolean resumeThread(Thread thread);
 
 
     public hs203t003(String[] arg) {
@@ -82,10 +83,10 @@
         MyThread mt = new MyThread();
         try {
             mt.start();
-            // check if we can can pop the thread.
-            // we can not do redefine/pop frame on run method.
+            // Check if we can can pop the thread.
+            // We can not do redefine/pop frame on run method.
             while (!MyThread.resume.get());
-            // sleep for some few secs to get redefined.
+            // Sleep for some few secs to get redefined.
             while (!isRedefined()) {
                 if (!agentStatus()) {
                     System.out.println("Failed to redefine class");
@@ -93,10 +94,26 @@
                 }
                 Thread.sleep(100);
             }
-            popThreadFrame(mt); // pop the frame.
-            resumeThread(mt);   // resume the thread.
+            // Wait for the thread to be suspended.
+            while (!isSuspended(mt)) {
+                if (!agentStatus()) {
+                    System.out.println("Failed to suspend thread");
+                    return passed;
+                }
+                Thread.sleep(100);
+            }
+            // Pop the frame.
+            if (!popThreadFrame(mt)) {
+                System.out.println("Failed to pop a frame = "
+                                   + mt.threadState);
+            }
+            // Resume the thread.
+            if(!resumeThread(mt)) {
+                System.out.println("Failed to resume the thread = "
+                                   + mt.threadState);
+            }
+            // Wait till the other thread completes its execution.
             mt.join();
-            // wait till the other thread completes its execution.
             System.out.println("Thread state after popping/redefining = "
                                + mt.threadState);
         } catch(Exception ie) {
--- a/test/hotspot/jtreg/vmTestbase/nsk/monitoring/share/StackTraceController.cpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/test/hotspot/jtreg/vmTestbase/nsk/monitoring/share/StackTraceController.cpp	Mon Oct 01 09:56:45 2018 +0100
@@ -29,31 +29,27 @@
 
 #define GET_OBJECT_CLASS(_class, _obj)\
     if (!NSK_JNI_VERIFY(env, (_class = \
-            NSK_CPP_STUB2(GetObjectClass, env, _obj)) != NULL))\
+            env->GetObjectClass(_obj)) != NULL))\
         return 2
 
 #define CALL_STATIC_VOID_NOPARAM(_class, _methodName)\
     GET_STATIC_METHOD_ID(method, _class, _methodName, "()V");\
-    if (!NSK_JNI_VERIFY_VOID(env, NSK_CPP_STUB3(CallStaticVoidMethod, env,\
-                            _class, method)))\
+    if (!NSK_JNI_VERIFY_VOID(env, env->CallStaticVoidMethod(_class, method)))\
         return 2
 
 #define GET_STATIC_METHOD_ID(_methodID, _class, _methodName, _sig)\
     if (!NSK_JNI_VERIFY(env, (_methodID = \
-            NSK_CPP_STUB4(GetStaticMethodID, env, _class,\
-                _methodName, _sig)) != NULL))\
+            env->GetStaticMethodID(_class, _methodName, _sig)) != NULL))\
         return 2
 
 #define GET_METHOD_ID(_methodID, _class, _methodName, _sig)\
     if (!NSK_JNI_VERIFY(env, (_methodID = \
-            NSK_CPP_STUB4(GetMethodID, env, _class,\
-                _methodName, _sig)) != NULL))\
+            env->GetMethodID(_class, _methodName, _sig)) != NULL))\
         return 2
 
 #define CALL_VOID_NOPARAM(_obj, _class, _methodName)\
     GET_METHOD_ID(method, _class, _methodName, "()V");\
-    if (!NSK_JNI_VERIFY_VOID(env, NSK_CPP_STUB3(CallVoidMethod, env, _obj,\
-                                                    method)))\
+    if (!NSK_JNI_VERIFY_VOID(env, env->CallVoidMethod(_obj, method)))\
         return 2
 
 JNIEXPORT jint JNICALL
@@ -71,18 +67,13 @@
         if (returnToJava) {
             GET_METHOD_ID(method, threadClass, "recursionJava", "(II)V");
             if (!NSK_JNI_VERIFY_VOID(env,
-                                     NSK_CPP_STUB5(CallIntMethod, env, obj,
-                                                   method, maxDepth,
-                                                   currentDepth))) {
+                                     env->CallIntMethod(obj, method, maxDepth, currentDepth))) {
                 return 1;
             }
         } else {
             GET_METHOD_ID(method, threadClass, "recursionNative", "(IIZ)I");
             if (!NSK_JNI_VERIFY_VOID(env,
-                                     NSK_CPP_STUB6(CallIntMethod, env, obj,
-                                                   method, maxDepth,
-                                                   currentDepth,
-                                                   returnToJava))) {
+                                     env->CallIntMethod(obj, method, maxDepth, currentDepth, returnToJava))) {
                 return 1;
             }
         }
--- a/test/hotspot/jtreg/vmTestbase/nsk/monitoring/share/ThreadController.cpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/test/hotspot/jtreg/vmTestbase/nsk/monitoring/share/ThreadController.cpp	Mon Oct 01 09:56:45 2018 +0100
@@ -31,131 +31,121 @@
 
 #define FIND_CLASS(_class, _className)\
     if (!NSK_JNI_VERIFY(env, (_class = \
-            NSK_CPP_STUB2(FindClass, env, _className)) != NULL))\
+            env->FindClass(_className)) != NULL))\
         return
 
 #define GET_OBJECT_CLASS(_class, _obj)\
     if (!NSK_JNI_VERIFY(env, (_class = \
-            NSK_CPP_STUB2(GetObjectClass, env, _obj)) != NULL))\
+            env->GetObjectClass(_obj)) != NULL))\
         return
 
 #define GET_STATIC_FIELD_ID(_fieldID, _class, _fieldName, _fieldSig)\
     if (!NSK_JNI_VERIFY(env, (_fieldID = \
-            NSK_CPP_STUB4(GetStaticFieldID, env, _class,\
-                _fieldName, _fieldSig)) != NULL))\
+            env->GetStaticFieldID(_class, _fieldName, _fieldSig)) != NULL))\
         return
 
 #define GET_STATIC_OBJ_FIELD(_value, _class, _fieldName, _fieldSig)\
     GET_STATIC_FIELD_ID(field, _class, _fieldName, _fieldSig);\
-    _value = NSK_CPP_STUB3(GetStaticObjectField, env, _class, \
-                                field)
+    _value = env->GetStaticObjectField(_class, field)
 
 #define GET_STATIC_BOOL_FIELD(_value, _class, _fieldName)\
     GET_STATIC_FIELD_ID(field, _class, _fieldName, "Z");\
-    _value = NSK_CPP_STUB3(GetStaticBooleanField, env, _class, field)
+    _value = env->GetStaticBooleanField(_class, field)
 
 #define GET_FIELD_ID(_fieldID, _class, _fieldName, _fieldSig)\
     if (!NSK_JNI_VERIFY(env, (_fieldID = \
-            NSK_CPP_STUB4(GetFieldID, env, _class,\
-                _fieldName, _fieldSig)) != NULL))\
+            env->GetFieldID(_class, _fieldName, _fieldSig)) != NULL))\
         return
 
 #define GET_INT_FIELD(_value, _obj, _class, _fieldName)\
     GET_FIELD_ID(field, _class, _fieldName, "I");\
-    _value = NSK_CPP_STUB3(GetIntField, env, _obj, field)
+    _value = env->GetIntField(_obj, field)
 
 #define GET_BOOL_FIELD(_value, _obj, _class, _fieldName)\
     GET_FIELD_ID(field, _class, _fieldName, "Z");\
-    _value = NSK_CPP_STUB3(GetBooleanField, env, _obj, field)
+    _value = env->GetBooleanField(_obj, field)
 
 #define GET_LONG_FIELD(_value, _obj, _class, _fieldName)\
     GET_FIELD_ID(field, _class, _fieldName, "J");\
-    _value = NSK_CPP_STUB3(GetLongField, env, _obj, field)
+    _value = env->GetLongField(_obj, field)
 
 #define GET_STATIC_INT_FIELD(_value, _class, _fieldName)\
     GET_STATIC_FIELD_ID(field, _class, _fieldName, "I");\
-    _value = NSK_CPP_STUB3(GetStaticIntField, env, _class, field)
+    _value = env->GetStaticIntField(_class, field)
 
 #define SET_INT_FIELD(_obj, _class, _fieldName, _newValue)\
     GET_FIELD_ID(field, _class, _fieldName, "I");\
-    NSK_CPP_STUB4(SetIntField, env, _obj, field, _newValue)
+    env->SetIntField(_obj, field, _newValue)
 
 #define GET_OBJ_FIELD(_value, _obj, _class, _fieldName, _fieldSig)\
     GET_FIELD_ID(field, _class, _fieldName, _fieldSig);\
-    _value = NSK_CPP_STUB3(GetObjectField, env, _obj, field)
+    _value = env->GetObjectField(_obj, field)
 
 
 #define GET_ARR_ELEMENT(_arr, _index)\
-    NSK_CPP_STUB3(GetObjectArrayElement, env, _arr, _index)
+    env->GetObjectArrayElement(_arr, _index)
 
 #define SET_ARR_ELEMENT(_arr, _index, _newValue)\
-    NSK_CPP_STUB4(SetObjectArrayElement, env, _arr, _index, _newValue)
+    env->SetObjectArrayElement(_arr, _index, _newValue)
 
 #define GET_STATIC_METHOD_ID(_methodID, _class, _methodName, _sig)\
     if (!NSK_JNI_VERIFY(env, (_methodID = \
-            NSK_CPP_STUB4(GetStaticMethodID, env, _class,\
-                _methodName, _sig)) != NULL))\
+            env->GetStaticMethodID(_class, _methodName, _sig)) != NULL))\
         return
 
 #define GET_METHOD_ID(_methodID, _class, _methodName, _sig)\
     if (!NSK_JNI_VERIFY(env, (_methodID = \
-            NSK_CPP_STUB4(GetMethodID, env, _class,\
-                _methodName, _sig)) != NULL))\
+            env->GetMethodID(_class, _methodName, _sig)) != NULL))\
         return
 
 #define CALL_STATIC_VOID_NOPARAM(_class, _methodName)\
     GET_STATIC_METHOD_ID(method, _class, _methodName, "()V");\
-    if (!NSK_JNI_VERIFY_VOID(env, NSK_CPP_STUB3(CallStaticVoidMethod, env,\
-                            _class, method)))\
+    if (!NSK_JNI_VERIFY_VOID(env, env->CallStaticVoidMethod(_class, method)))\
         return
 
 #define CALL_STATIC_VOID(_class, _methodName, _sig, _param)\
     GET_STATIC_METHOD_ID(method, _class, _methodName, _sig);\
-    if (!NSK_JNI_VERIFY_VOID(env, NSK_CPP_STUB4(CallStaticVoidMethod, env,\
-                                                    _class, method, _param)))\
+    if (!NSK_JNI_VERIFY_VOID(env, env->CallStaticVoidMethod(_class, method, _param)))\
         return
 
 #define CALL_STATIC_OBJ(_value, _class, _methodName, _sig, _param)\
     GET_STATIC_METHOD_ID(method, _class, _methodName, _sig);\
-    _value = NSK_CPP_STUB4(CallStaticObjectMethod, env, _class, method, _param)
+    _value = env->CallStaticObjectMethod(_class, method, _param)
 
 #define CALL_VOID_NOPARAM(_obj, _class, _methodName)\
     GET_METHOD_ID(method, _class, _methodName, "()V");\
-    if (!NSK_JNI_VERIFY_VOID(env, NSK_CPP_STUB3(CallVoidMethod, env, _obj,\
-                                                    method)))\
+    if (!NSK_JNI_VERIFY_VOID(env, env->CallVoidMethod(_obj, method)))\
         return
 
 #define CALL_VOID(_obj, _class, _methodName, _sig, _param)\
     GET_METHOD_ID(method, _class, _methodName, "()V");\
-    if (!NSK_JNI_VERIFY_VOID(env, NSK_CPP_STUB4(CallVoidMethod, env, _obj,\
-                                                    method, _param)))\
+    if (!NSK_JNI_VERIFY_VOID(env, env->CallVoidMethod(_obj, method, _param)))\
         return
 
 #define CALL_VOID2(_obj, _class, _methodName, _sig, _param1, _param2)\
     GET_METHOD_ID(method, _class, _methodName, _sig);\
-    if (!NSK_JNI_VERIFY_VOID(env, NSK_CPP_STUB5(CallVoidMethod, env, _obj, \
-                                                    method, _param1, _param2)))\
+    if (!NSK_JNI_VERIFY_VOID(env, env->CallVoidMethod(_obj, method, _param1, _param2)))\
         return
 
 #define CALL_INT_NOPARAM(_value, _obj, _class, _methodName)\
     GET_METHOD_ID(method, _class, _methodName, "()I");\
-    _value = NSK_CPP_STUB3(CallIntMethod, env, _obj, method)
+    _value = env->CallIntMethod(_obj, method)
 
 #define NEW_OBJ(_obj, _class, _constructorName, _sig, _params)\
     GET_METHOD_ID(method, _class, _constructorName, _sig);\
     if (!NSK_JNI_VERIFY(env, (_obj = \
-            NSK_CPP_STUB4(NewObject, env, _class, method, _params)) != NULL))\
+            env->NewObject(_class, method, _params)) != NULL))\
         return
 
 #define MONITOR_ENTER(x) \
-    NSK_JNI_VERIFY(env, NSK_CPP_STUB2(MonitorEnter, env, x) == 0)
+    NSK_JNI_VERIFY(env, env->MonitorEnter(x) == 0)
 
 #define MONITOR_EXIT(x) \
-    NSK_JNI_VERIFY(env, NSK_CPP_STUB2(MonitorExit, env, x) == 0)
+    NSK_JNI_VERIFY(env, env->MonitorExit(x) == 0)
 
 #define TRACE(msg)\
    GET_OBJ_FIELD(logger, obj, threadClass, "logger", "Lnsk/share/Log$Logger;");\
-   jmsg = NSK_CPP_STUB2(NewStringUTF, env, msg);\
+   jmsg = env->NewStringUTF(msg);\
    CALL_VOID2(logger, loggerClass, "trace",\
                            "(ILjava/lang/String;)V", 50, jmsg)
 
@@ -497,29 +487,29 @@
         jint state;
 
         if(!NSK_VERIFY(
-             NSK_CPP_STUB2(GetJavaVM, env, &vm) == 0)) {
+             env->GetJavaVM(&vm) == 0)) {
             return NULL;
         }
 
         if(!NSK_VERIFY(
-             NSK_CPP_STUB3(GetEnv, vm, (void **)&jvmti, JVMTI_VERSION_1)
+             vm->GetEnv((void **)&jvmti, JVMTI_VERSION_1)
                     == JNI_OK)) {
             return NULL;
         }
 
         if(!NSK_VERIFY(
-             NSK_CPP_STUB3(GetThreadState, jvmti, (jthread)thread, &state)
+             jvmti->GetThreadState((jthread)thread, &state)
              == JVMTI_ERROR_NONE)) {
             return NULL;
         }
 
         stateName = getStateName(env, state);
-        if (!NSK_JNI_VERIFY(env, (ThreadState = NSK_CPP_STUB2(FindClass, env, "java/lang/Thread$State")) != NULL))
+        if (!NSK_JNI_VERIFY(env, (ThreadState = env->FindClass("java/lang/Thread$State")) != NULL))
             return NULL;
 
-        if (!NSK_JNI_VERIFY(env, (method = NSK_CPP_STUB4(GetStaticMethodID, env, ThreadState, "valueOf", "(Ljava/lang/String;)Ljava/lang/Thread$State;")) != NULL))
+        if (!NSK_JNI_VERIFY(env, (method = env->GetStaticMethodID(ThreadState, "valueOf", "(Ljava/lang/String;)Ljava/lang/Thread$State;")) != NULL))
             return NULL;
-        threadState = NSK_CPP_STUB4(CallStaticObjectMethod, env, ThreadState, method, stateName);
+        threadState = env->CallStaticObjectMethod(ThreadState, method, stateName);
 
         return threadState;
     }
--- a/test/hotspot/jtreg/vmTestbase/nsk/monitoring/share/thread/Deadlock.cpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/test/hotspot/jtreg/vmTestbase/nsk/monitoring/share/thread/Deadlock.cpp	Mon Oct 01 09:56:45 2018 +0100
@@ -27,34 +27,31 @@
 
 #define FIND_CLASS(_class, _className)\
         if (!NSK_JNI_VERIFY(env, (_class = \
-             NSK_CPP_STUB2(FindClass, env, _className)) != NULL))\
+             env->FindClass(_className)) != NULL))\
                 return
 
 #define GET_OBJECT_CLASS(_class, _obj)\
         if (!NSK_JNI_VERIFY(env, (_class = \
-             NSK_CPP_STUB2(GetObjectClass, env, _obj)) != NULL))\
+             env->GetObjectClass(_obj)) != NULL))\
                 return
 
 #define GET_OBJ_FIELD(_value, _obj, _class, _fieldName, _fieldSig)\
         GET_FIELD_ID(field, _class, _fieldName, _fieldSig);\
-        _value = NSK_CPP_STUB3(GetObjectField, env, _obj, field)
+        _value = env->GetObjectField(_obj, field)
 
 #define GET_FIELD_ID(_fieldID, _class, _fieldName, _fieldSig)\
         if (!NSK_JNI_VERIFY(env, (_fieldID = \
-             NSK_CPP_STUB4(GetFieldID, env, _class,\
-             _fieldName, _fieldSig)) != NULL))\
+             env->GetFieldID(_class, _fieldName, _fieldSig)) != NULL))\
                 return
 
 #define GET_METHOD_ID(_methodID, _class, _methodName, _sig)\
         if (!NSK_JNI_VERIFY(env, (_methodID = \
-             NSK_CPP_STUB4(GetMethodID, env, _class,\
-             _methodName, _sig)) != NULL)) \
+             env->GetMethodID(_class, _methodName, _sig)) != NULL)) \
                 return
 
 #define CALL_VOID_NOPARAM(_obj, _class, _methodName)\
             GET_METHOD_ID(method, _class, _methodName, "()V");\
-        if (!NSK_JNI_VERIFY_VOID(env, NSK_CPP_STUB3(CallVoidMethod, env, _obj,\
-             method))) \
+        if (!NSK_JNI_VERIFY_VOID(env, env->CallVoidMethod(_obj, method))) \
                 return
 
 /*
--- a/test/hotspot/jtreg/vmTestbase/nsk/monitoring/share/thread/LockingThreads.cpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/test/hotspot/jtreg/vmTestbase/nsk/monitoring/share/thread/LockingThreads.cpp	Mon Oct 01 09:56:45 2018 +0100
@@ -27,34 +27,31 @@
 
 #define FIND_CLASS(_class, _className)\
         if (!NSK_JNI_VERIFY(env, (_class = \
-             NSK_CPP_STUB2(FindClass, env, _className)) != NULL))\
+             env->FindClass(_className)) != NULL))\
                 return
 
 #define GET_OBJECT_CLASS(_class, _obj)\
         if (!NSK_JNI_VERIFY(env, (_class = \
-             NSK_CPP_STUB2(GetObjectClass, env, _obj)) != NULL))\
+             env->GetObjectClass(_obj)) != NULL))\
                 return
 
 #define GET_OBJ_FIELD(_value, _obj, _class, _fieldName, _fieldSig)\
         GET_FIELD_ID(field, _class, _fieldName, _fieldSig);\
-        _value = NSK_CPP_STUB3(GetObjectField, env, _obj, field)
+        _value = env->GetObjectField(_obj, field)
 
 #define GET_FIELD_ID(_fieldID, _class, _fieldName, _fieldSig)\
         if (!NSK_JNI_VERIFY(env, (_fieldID = \
-             NSK_CPP_STUB4(GetFieldID, env, _class,\
-             _fieldName, _fieldSig)) != NULL))\
+             env->GetFieldID(_class, _fieldName, _fieldSig)) != NULL))\
                 return
 
 #define GET_METHOD_ID(_methodID, _class, _methodName, _sig)\
         if (!NSK_JNI_VERIFY(env, (_methodID = \
-             NSK_CPP_STUB4(GetMethodID, env, _class,\
-             _methodName, _sig)) != NULL))\
+             env->GetMethodID(_class, _methodName, _sig)) != NULL))\
                 return
 
 #define CALL_VOID_NOPARAM(_obj, _class, _methodName)\
             GET_METHOD_ID(method, _class, _methodName, "()V");\
-        if (!NSK_JNI_VERIFY_VOID(env, NSK_CPP_STUB3(CallVoidMethod, env, _obj,\
-             method)))\
+        if (!NSK_JNI_VERIFY_VOID(env, env->CallVoidMethod(_obj, method)))\
                 return
 /*
  * Class:     nsk_monitoring_share_thread_LockingThreads_Thread1
--- a/test/hotspot/jtreg/vmTestbase/nsk/monitoring/share/thread/RecursiveMonitoringThread.cpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/test/hotspot/jtreg/vmTestbase/nsk/monitoring/share/thread/RecursiveMonitoringThread.cpp	Mon Oct 01 09:56:45 2018 +0100
@@ -29,123 +29,113 @@
 
 #define FIND_CLASS(_class, _className)\
     if (!NSK_JNI_VERIFY(env, (_class = \
-            NSK_CPP_STUB2(FindClass, env, _className)) != NULL))\
+            env->FindClass(_className)) != NULL))\
         return
 
 #define GET_OBJECT_CLASS(_class, _obj)\
     if (!NSK_JNI_VERIFY(env, (_class = \
-            NSK_CPP_STUB2(GetObjectClass, env, _obj)) != NULL))\
+            env->GetObjectClass(_obj)) != NULL))\
         return
 
 #define GET_STATIC_FIELD_ID(_fieldID, _class, _fieldName, _fieldSig)\
     if (!NSK_JNI_VERIFY(env, (_fieldID = \
-            NSK_CPP_STUB4(GetStaticFieldID, env, _class,\
-                _fieldName, _fieldSig)) != NULL))\
+            env->GetStaticFieldID(_class, _fieldName, _fieldSig)) != NULL))\
         return
 
 #define GET_STATIC_OBJ_FIELD(_value, _class, _fieldName, _fieldSig)\
     GET_STATIC_FIELD_ID(field, _class, _fieldName, _fieldSig);\
-    _value = NSK_CPP_STUB3(GetStaticObjectField, env, _class, \
-                                field)
+    _value = env->GetStaticObjectField(_class, field)
 
 #define GET_STATIC_BOOL_FIELD(_value, _class, _fieldName)\
     GET_STATIC_FIELD_ID(field, _class, _fieldName, "Z");\
-    _value = NSK_CPP_STUB3(GetStaticBooleanField, env, _class, field)
+    _value = env->GetStaticBooleanField(_class, field)
 
 #define GET_FIELD_ID(_fieldID, _class, _fieldName, _fieldSig)\
     if (!NSK_JNI_VERIFY(env, (_fieldID = \
-            NSK_CPP_STUB4(GetFieldID, env, _class,\
-                _fieldName, _fieldSig)) != NULL))\
+            env->GetFieldID(_class, _fieldName, _fieldSig)) != NULL))\
         return
 
 #define GET_INT_FIELD(_value, _obj, _class, _fieldName)\
     GET_FIELD_ID(field, _class, _fieldName, "I");\
-    _value = NSK_CPP_STUB3(GetIntField, env, _obj, field)
+    _value = env->GetIntField(_obj, field)
 
 #define GET_LONG_FIELD(_value, _obj, _class, _fieldName)\
     GET_FIELD_ID(field, _class, _fieldName, "J");\
-    _value = NSK_CPP_STUB3(GetLongField, env, _obj, field)
+    _value = env->GetLongField(_obj, field)
 
 #define GET_STATIC_INT_FIELD(_value, _class, _fieldName)\
     GET_STATIC_FIELD_ID(field, _class, _fieldName, "I");\
-    _value = NSK_CPP_STUB3(GetStaticIntField, env, _class, field)
+    _value = env->GetStaticIntField(_class, field)
 
 #define SET_INT_FIELD(_obj, _class, _fieldName, _newValue)\
     GET_FIELD_ID(field, _class, _fieldName, "I");\
-    NSK_CPP_STUB4(SetIntField, env, _obj, field, _newValue)
+    env->SetIntField(_obj, field, _newValue)
 
 #define GET_OBJ_FIELD(_value, _obj, _class, _fieldName, _fieldSig)\
     GET_FIELD_ID(field, _class, _fieldName, _fieldSig);\
-    _value = NSK_CPP_STUB3(GetObjectField, env, _obj, field)
+    _value = env->GetObjectField(_obj, field)
 
 
 #define GET_ARR_ELEMENT(_arr, _index)\
-    NSK_CPP_STUB3(GetObjectArrayElement, env, _arr, _index)
+    env->GetObjectArrayElement(_arr, _index)
 
 #define SET_ARR_ELEMENT(_arr, _index, _newValue)\
-    NSK_CPP_STUB4(SetObjectArrayElement, env, _arr, _index, _newValue)
+    env->SetObjectArrayElement(_arr, _index, _newValue)
 
 #define GET_STATIC_METHOD_ID(_methodID, _class, _methodName, _sig)\
     if (!NSK_JNI_VERIFY(env, (_methodID = \
-            NSK_CPP_STUB4(GetStaticMethodID, env, _class,\
-                _methodName, _sig)) != NULL))\
+            env->GetStaticMethodID(_class, _methodName, _sig)) != NULL))\
         return
 
 #define GET_METHOD_ID(_methodID, _class, _methodName, _sig)\
     if (!NSK_JNI_VERIFY(env, (_methodID = \
-            NSK_CPP_STUB4(GetMethodID, env, _class,\
-                _methodName, _sig)) != NULL))\
+            env->GetMethodID(_class, _methodName, _sig)) != NULL))\
         return
 
 #define CALL_STATIC_VOID_NOPARAM(_class, _methodName)\
     GET_STATIC_METHOD_ID(method, _class, _methodName, "()V");\
-    if (!NSK_JNI_VERIFY_VOID(env, NSK_CPP_STUB3(CallStaticVoidMethod, env,\
-                            _class, method)))\
+    if (!NSK_JNI_VERIFY_VOID(env, env->CallStaticVoidMethod(_class, method)))\
         return
 
 #define CALL_STATIC_VOID(_class, _methodName, _sig, _param)\
     GET_STATIC_METHOD_ID(method, _class, _methodName, _sig);\
-    if (!NSK_JNI_VERIFY_VOID(env, NSK_CPP_STUB4(CallStaticVoidMethod, env,\
-                                                    _class, method, _param)))\
+    if (!NSK_JNI_VERIFY_VOID(env, env->CallStaticVoidMethod(_class, method, _param)))\
         return
 
 #define CALL_VOID_NOPARAM(_obj, _class, _methodName)\
     GET_METHOD_ID(method, _class, _methodName, "()V");\
-    if (!NSK_JNI_VERIFY_VOID(env, NSK_CPP_STUB3(CallVoidMethod, env, _obj,\
-                                                    method)))\
+    if (!NSK_JNI_VERIFY_VOID(env, env->CallVoidMethod(_obj, method)))\
         return
 
 #define CALL_VOID(_obj, _class, _methodName, _sig, _param)\
     GET_METHOD_ID(method, _class, _methodName, _sig);\
-    if (!NSK_JNI_VERIFY_VOID(env, NSK_CPP_STUB4(CallVoidMethod, env, _obj,\
-                                                    method, _param)))\
+    if (!NSK_JNI_VERIFY_VOID(env, env->CallVoidMethod(_obj, method, _param)))\
         return
 
 #define CALL_VOID2(_obj, _class, _methodName, _sig, _param1, _param2)\
     GET_METHOD_ID(method, _class, _methodName, _sig);\
-    if (!NSK_JNI_VERIFY_VOID(env, NSK_CPP_STUB5(CallVoidMethod, env, _obj, \
-                                                    method, _param1, _param2)))\
+    if (!NSK_JNI_VERIFY_VOID(env, env->CallVoidMethod(_obj, method, _param1, _param2)))\
         return
 
 #define CALL_INT_NOPARAM(_value, _obj, _class, _methodName)\
     GET_METHOD_ID(method, _class, _methodName, "()I");\
-    _value = NSK_CPP_STUB3(CallIntMethod, env, _obj, method)
+    _value = env->CallIntMethod(_obj, method)
 
 #define NEW_OBJ(_obj, _class, _constructorName, _sig, _params)\
     GET_METHOD_ID(method, _class, _constructorName, _sig);\
     if (!NSK_JNI_VERIFY(env, (_obj = \
-            NSK_CPP_STUB4(NewObject, env, _class, method, _params)) != NULL))\
+            env->NewObject(_class, method, _params)) != NULL))\
         return
 
 #define MONITOR_ENTER(x) \
-    NSK_JNI_VERIFY(env, NSK_CPP_STUB2(MonitorEnter, env, x) == 0)
+    NSK_JNI_VERIFY(env, env->MonitorEnter(x) == 0)
 
 #define MONITOR_EXIT(x) \
-    NSK_JNI_VERIFY(env, NSK_CPP_STUB2(MonitorExit, env, x) == 0)
+    NSK_JNI_VERIFY(env, env->MonitorExit(x) == 0)
 
 #define TRACE(msg)\
    GET_OBJ_FIELD(logger, obj, threadClass, "logger", "Lnsk/share/Log$Logger;");\
-   jmsg = NSK_CPP_STUB2(NewStringUTF, env, msg);\
+   jmsg = env->NewStringUTF(msg);\
    CALL_VOID2(logger, loggerClass, "trace",\
                            "(ILjava/lang/String;)V", 50, jmsg)
 
--- a/test/hotspot/jtreg/vmTestbase/nsk/share/JVMTIagent.cpp	Wed Sep 26 18:11:00 2018 +0100
+++ b/test/hotspot/jtreg/vmTestbase/nsk/share/JVMTIagent.cpp	Mon Oct 01 09:56:45 2018 +0100
@@ -160,10 +160,8 @@
         lock(jni_env);
         display(0, "#### JVMTIagent: ClassLoad: >>>>>>>> entered the raw monitor \"eventLock\" ####\n");
 
-        if (!NSK_JVMTI_VERIFY(NSK_CPP_STUB4(GetClassSignature,
-                jvmti_env, klass, &cls_sig, /*&generic*/NULL)))
-            NSK_CPP_STUB2(FatalError, jni_env,
-                "JVMTIagent: failed to get class signature\n");
+        if (!NSK_JVMTI_VERIFY(jvmti_env->GetClassSignature(klass, &cls_sig, /*&generic*/NULL)))
+            jni_env->FatalError("JVMTIagent: failed to get class signature\n");
         else {
             if (shortTestName != NULL) {
                 if (strstr((const char*) cls_sig, shortTestName) != NULL) {
@@ -245,14 +243,11 @@
 
     if (hotswap == HOTSWAP_EVERY_EXCEPTION ||
             hotswap == HOTSWAP_EVERY_EXCEPTION_FOR_EVERY_CLASS) {
-        if (!NSK_JVMTI_VERIFY(NSK_CPP_STUB3(GetMethodDeclaringClass,
-                jvmti_env, method, &decl_clazz)))
-            NSK_CPP_STUB2(FatalError, jni_env,
-                "JVMTIagent: failed to get method declaring class\n");
+        if (!NSK_JVMTI_VERIFY(jvmti_env->GetMethodDeclaringClass(method, &decl_clazz)))
+            jni_env->FatalError("JVMTIagent: failed to get method declaring class\n");
 
         if (findAndHotSwap(jni_env, decl_clazz) != 0)
-            NSK_CPP_STUB2(FatalError, jni_env,
-                "JVMTIagent: failed to hotswap class\n");
+            jni_env->FatalError("JVMTIagent: failed to hotswap class\n");
     }
 }
 
@@ -419,14 +414,11 @@
     getVerdict(jni_env, "SingleStep");
 
     if (hotswap == HOTSWAP_EVERY_SINGLE_STEP) {
-        if (!NSK_JVMTI_VERIFY(NSK_CPP_STUB3(GetMethodDeclaringClass,
-                jvmti_env, method, &decl_clazz)))
-            NSK_CPP_STUB2(FatalError, jni_env,
-                "JVMTIagent: failed to get method declaring class\n");
+        if (!NSK_JVMTI_VERIFY(jvmti_env->GetMethodDeclaringClass(method, &decl_clazz)))
+            jni_env->FatalError("JVMTIagent: failed to get method declaring class\n");
 
         if (findAndHotSwap(jni_env, decl_clazz) != 0)
-            NSK_CPP_STUB2(FatalError, jni_env,
-                "JVMTIagent: failed to hotswap class\n");
+            jni_env->FatalError("JVMTIagent: failed to hotswap class\n");
     }
 }
 
@@ -443,14 +435,11 @@
 
     if (hotswap == HOTSWAP_EVERY_METHOD_ENTRY ||
             hotswap == HOTSWAP_EVERY_METHOD_ENTRY_FOR_EVERY_CLASS) {
-        if (!NSK_JVMTI_VERIFY(NSK_CPP_STUB3(GetMethodDeclaringClass,
-                jvmti_env, method, &decl_clazz)))
-            NSK_CPP_STUB2(FatalError, jni_env,
-                "JVMTIagent: failed to get method declaring class\n");
+        if (!NSK_JVMTI_VERIFY(jvmti_env->GetMethodDeclaringClass(method, &decl_clazz)))
+            jni_env->FatalError("JVMTIagent: failed to get method declaring class\n");
 
         if (findAndHotSwap(jni_env, decl_clazz) != 0)
-            NSK_CPP_STUB2(FatalError, jni_env,
-                "JVMTIagent: failed to hotswap class\n");
+            jni_env->FatalError("JVMTIagent: failed to hotswap class\n");
     }
 }
 
@@ -477,30 +466,23 @@
 
     if (hotswap == HOTSWAP_EVERY_EXCEPTION ||
             hotswap == HOTSWAP_EVERY_EXCEPTION_FOR_EVERY_CLASS) {
-        if (!NSK_JVMTI_VERIFY(NSK_CPP_STUB3(GetMethodDeclaringClass,
-                jvmti_env, method, &decl_clazz)))
-            NSK_CPP_STUB2(FatalError, jni_env,
-                "JVMTIagent: failed to get method declaring class\n");
+        if (!NSK_JVMTI_VERIFY(jvmti_env->GetMethodDeclaringClass(method, &decl_clazz)))
+            jni_env->FatalError("JVMTIagent: failed to get method declaring class\n");
 
         if (findAndHotSwap(jni_env, decl_clazz) != 0)
-            NSK_CPP_STUB2(FatalError, jni_env,
-                "JVMTIagent: failed to hotswap class\n");
+            jni_env->FatalError("JVMTIagent: failed to hotswap class\n");
     }
 }
 /************************/
 
 static void lock(JNIEnv *jni_env) {
-    if (!NSK_JVMTI_VERIFY(NSK_CPP_STUB2(RawMonitorEnter,
-            jvmti, eventLock)))
-        NSK_CPP_STUB2(FatalError, jni_env,
-            "JVMTIagent: failed to enter a raw monitor\n");
+    if (!NSK_JVMTI_VERIFY(jvmti->RawMonitorEnter(eventLock)))
+        jni_env->FatalError("JVMTIagent: failed to enter a raw monitor\n");
 }
 
 static void unlock(JNIEnv *jni_env) {
-    if (!NSK_JVMTI_VERIFY(NSK_CPP_STUB2(RawMonitorExit,
-            jvmti, eventLock)))
-        NSK_CPP_STUB2(FatalError, jni_env,
-            "JVMTIagent: failed to exit a raw monitor\n");
+    if (!NSK_JVMTI_VERIFY(jvmti->RawMonitorExit(eventLock)))
+        jni_env->FatalError("JVMTIagent: failed to exit a raw monitor\n");
 }
 
 JNIEXPORT jint JNICALL
@@ -516,10 +498,8 @@
     }
 
     /* get supported JVMTI capabilities */
-    if (!NSK_JVMTI_VERIFY(NSK_CPP_STUB2(GetCapabilities,
-            jvmti, &capabil)))
-        NSK_CPP_STUB2(FatalError, jni_env,
-            "JVMTIagent: failed to get capabilities\n");
+    if (!NSK_JVMTI_VERIFY(jvmti->GetCapabilities(&capabil)))
+        jni_env->FatalError("JVMTIagent: failed to get capabilities\n");
     if (capabil.can_redefine_classes != 1) { /* ???????????? */
         printf("ERROR: JVMTIagent: Class File Redefinition (HotSwap) is not implemented in this VM\n");
         return 1;
@@ -574,16 +554,14 @@
             return 1;
     }
 
-    if (!NSK_JNI_VERIFY(jni_env, (shortTestName = NSK_CPP_STUB3(GetStringUTFChars,
-            jni_env, shortName, NULL)) != NULL)) {
+    if (!NSK_JNI_VERIFY(jni_env, (shortTestName = jni_env->GetStringUTFChars(shortName, NULL)) != NULL)) {
         printf("ERROR: JVMTIagent: unable to get UTF-8 characters of the string\n");
         return 1;
     }
     display(0, "#### JVMTIagent: short name of current test is \"%s\"\n",
         shortTestName);
 
-    if (!NSK_JNI_VERIFY(jni_env, (rasCls = NSK_CPP_STUB2(NewGlobalRef,
-            jni_env, cls)) != NULL)) {
+    if (!NSK_JNI_VERIFY(jni_env, (rasCls = jni_env->NewGlobalRef(cls)) != NULL)) {
         printf("ERROR JVMTIagent: unable to create a new global reference of the class \"RASagent\"\n");
         return 1;
     }
@@ -605,37 +583,31 @@
 
     if ((_clsInfo = (class_info*)
             malloc(sizeof(class_info))) == NULL)
-        NSK_CPP_STUB2(FatalError, jni_env,
-            "JVMTIagent: cannot allocate memory for class_info\n");
+        jni_env->FatalError("JVMTIagent: cannot allocate memory for class_info\n");
 
     /* fill the structure class_info */
     _clsInfo->clazzsig = cls_sig;
 
-    if (!NSK_JNI_VERIFY(jni_env, ((*_clsInfo).cls = NSK_CPP_STUB2(NewGlobalRef,
-            jni_env, clazz)) != NULL)) {
+    if (!NSK_JNI_VERIFY(jni_env, ((*_clsInfo).cls = jni_env->NewGlobalRef(clazz)) != NULL)) {
         printf("ERROR: JVMTIagent: unable to create a new global reference of class \"%s\"\n",
             _clsInfo->clazzsig);
         free(_clsInfo);
         deallocClsInfo(jni_env);
-        NSK_CPP_STUB2(FatalError, jni_env,
-            "JVMTIagent: unable to create a new global reference of class\n");
+        jni_env->FatalError("JVMTIagent: unable to create a new global reference of class\n");
     }
 
     if (!NSK_JNI_VERIFY(jni_env, (mid =
-        NSK_CPP_STUB4(GetStaticMethodID, jni_env, rasCls,
-            "loadFromClassFile", "(Ljava/lang/String;)[B")) != NULL))
-        NSK_CPP_STUB2(FatalError, jni_env,
-            "JVMTIagent: unable to get ID of the method \"loadFromClassFile\"\n");
+        jni_env->GetStaticMethodID(rasCls, "loadFromClassFile", "(Ljava/lang/String;)[B")) != NULL))
+        jni_env->FatalError("JVMTIagent: unable to get ID of the method \"loadFromClassFile\"\n");
 
-    classBytes = (jbyteArray) NSK_CPP_STUB4(CallStaticObjectMethod,
-        jni_env, rasCls, mid, NSK_CPP_STUB2(NewStringUTF, jni_env, cls_sig));
+    classBytes = (jbyteArray) jni_env->CallStaticObjectMethod(rasCls, mid, jni_env->NewStringUTF(cls_sig));
 
     clearJavaException(jni_env);
 
-    (*_clsInfo).bCount = NSK_CPP_STUB2(GetArrayLength, jni_env, classBytes);
+    (*_clsInfo).bCount = jni_env->GetArrayLength(classBytes);
 
     (*_clsInfo).clsBytes =
-        NSK_CPP_STUB3(GetByteArrayElements, jni_env, classBytes, &isCopy);
+        jni_env->GetByteArrayElements(classBytes, &isCopy);
 
     _clsInfo->next = NULL;
 
@@ -653,17 +625,15 @@
 static void deallocClsInfo(JNIEnv *jni_env) {
     class_info *clsInfoCurr = clsInfoFst;
 
-    NSK_TRACE(NSK_CPP_STUB2(DeleteGlobalRef, jni_env, rasCls));
+    NSK_TRACE(jni_env->DeleteGlobalRef(rasCls));
 
     while(clsInfoCurr != NULL) {
         class_info *_clsInfo = clsInfoCurr;
 
-        if (!NSK_JVMTI_VERIFY(NSK_CPP_STUB2(Deallocate,
-                jvmti, (unsigned char*) clsInfoCurr->clazzsig)))
-            NSK_CPP_STUB2(FatalError, jni_env,
-                "JVMTIagent: failed to deallocate memory for clazzsig\n");
+        if (!NSK_JVMTI_VERIFY(jvmti->Deallocate((unsigned char*) clsInfoCurr->clazzsig)))
+            jni_env->FatalError("JVMTIagent: failed to deallocate memory for clazzsig\n");
 
-        NSK_TRACE(NSK_CPP_STUB2(DeleteGlobalRef, jni_env, clsInfoCurr->cls));
+        NSK_TRACE(jni_env->DeleteGlobalRef(clsInfoCurr->cls));
 
         clsInfoCurr = (class_info*) clsInfoCurr->next;
 
@@ -679,10 +649,8 @@
     class_info *clsInfoCurr = clsInfoFst;
 
     display(1, "\n#### JVMTIagent: findAndHotSwap: obtaining class signature of class to be hotswap ...\n");
-    if (!NSK_JVMTI_VERIFY(NSK_CPP_STUB4(GetClassSignature,
-            jvmti, clazz, &clazzsig, /*&generic*/NULL)))
-        NSK_CPP_STUB2(FatalError, jni_env,
-            "JVMTIagent: findAndHotSwap: failed to get class signature\n");
+    if (!NSK_JVMTI_VERIFY(jvmti->GetClassSignature(clazz, &clazzsig, /*&generic*/NULL)))
+        jni_env->FatalError("JVMTIagent: findAndHotSwap: failed to get class signature\n");
     else {
         display(1, "#### JVMTIagent: findAndHotSwap: ... class signature obtained: \"%s\"\n",
             clazzsig);
@@ -696,10 +664,8 @@
                     hotswap == HOTSWAP_EVERY_EXCEPTION_FOR_EVERY_CLASS) {
                 display(1, "\n#### JVMTIagent: findAndHotSwap: going to hotswap tested class \"%s\" during execution of class \"%s\" ...\n",
                     clsInfoCurr->clazzsig, clazzsig);
-                if (!NSK_JVMTI_VERIFY(NSK_CPP_STUB2(Deallocate,
-                        jvmti, (unsigned char*) clazzsig)))
-                    NSK_CPP_STUB2(FatalError, jni_env,
-                        "JVMTIagent: findAndHotSwap: failed to deallocate memory for clazzsig\n");
+                if (!NSK_JVMTI_VERIFY(jvmti->Deallocate((unsigned char*) clazzsig)))
+                    jni_env->FatalError("JVMTIagent: findAndHotSwap: failed