Merge
diff --git a/.hgtags b/.hgtags
index 094a4a7..6325e39 100644
--- a/.hgtags
+++ b/.hgtags
@@ -1,3 +1,14 @@
+b14b1a25c459d80b5b8bdec7022ee6d61b532b1d jdk8u171-b05
+d3d59998d7502e1feaaff02be3e39657ec3b8a30 jdk8u152-b31
+7e0dd213885b68427048a32e0771c65b9628ed7d jdk8u152-b32
+5b2f35270afe5cd5f861a02c4a9a48e759b16c11 jdk8u152-b33
+2c635aa0b63fbceaa9e7738c3eba9ee5354d163f jdk8u152-b34
+e3ba95a3c4dd5fb1bddbe87634fce4439635c9dd jdk8u152-b35
+b16bf5aa789e4e2fab4e82b4ff20bb74ee0739d3 jdk8u171-b01
+62b336d24b4a92c020abeb5815b97873a004f3dc jdk8u171-b02
+2d8288d22880abc92fd1a50cfbb7cf0484d64fff jdk8u181-b00
+ff2d8936f62c2c59ba3853fdea5e03d3c2845866 jdk8u171-b03
+febef16b395febecbcd9f117bb359bdec0d227f1 jdk8u171-b04
 af08e8af4f3e527439502734b80218f40088bda4 jdk8u161-b12
 4ebcfc5247434271284014f7230dcd81e4c9fff9 jdk8u161-b11
 0c7774863b66c8d87610ac35a82a9bb4f71f9109 jdk8u161-b10
@@ -768,4 +779,6 @@
 ce33a5743988983a4e8e5bcff07bd0a32d6b2f31 jdk8u162-b09
 407c3752f9465860503c60bd5d2b0eed25e2983c jdk8u162-b10
 c49775823a756f1ff11b264ff2d5e8c51e08cf89 jdk8u162-b11
-b14b1a25c459d80b5b8bdec7022ee6d61b532b1d jdk8u171-b05
+0a2c9f41e37ba19b50fee4ea4381e66ca5dfc483 jdk8u162-b12
+f08daa77f272ceebe32170a71ae09b71c005506b jdk8u172-b03
+6e63a5933b67b8e437c9671958d44e4cc75d61c9 jdk8u172-b04
diff --git a/.hgtags-top-repo b/.hgtags-top-repo
index a8c3f5c..14a140d 100644
--- a/.hgtags-top-repo
+++ b/.hgtags-top-repo
@@ -826,3 +826,9 @@
 28f638905f78913e5b6dc89dd88e37223984a105 jdk8u171-b02
 f2d13f7195163a34af334e0613c953ddec40e115 jdk8u171-b03
 86b50f26a9d10245a7df1b4e0ef1189f1dfd1b25 jdk8u171-b04
+0efc15ed66b0c26b9434427f7db59d99b2669dc2 jdk8u171-b05
+e91f5717d8a5df396c8646da9b5a7bcd526bf288 jdk8u172-b00
+a0672a294b9aff852f35336932ddf3d46465f28c jdk8u172-b01
+315185c9100a22c0f881de8014623dd352eaf6f5 jdk8u172-b02
+7204958a8c003cc1c79d520d9e7a5c0157e783b3 jdk8u172-b03
+a80949c226a2d13ad5d8dd63b200a999538fa2c2 jdk8u172-b04
diff --git a/corba/.hgtags b/corba/.hgtags
index 4018f18..584055c 100644
--- a/corba/.hgtags
+++ b/corba/.hgtags
@@ -870,3 +870,9 @@
 28be709707f8b275aeaa2ed41338678620e3ef5f jdk8u171-b02
 d534205fffcf950a11ed37103f5a0c23fe14ee49 jdk8u171-b03
 0baf88a7b3880bbefdbb221e67a6ce96b0552033 jdk8u171-b04
+0c6a772d60b94de90907f2f6d4683ceac8aba54b jdk8u171-b05
+72dbc8d63308f5b04b9fd3e06d139d673f992212 jdk8u172-b00
+fbb7c1e76e59aabb85a70c81301f47b980f83225 jdk8u172-b01
+56874ff37e89559692d1314d48cbab574544b677 jdk8u172-b02
+65a52284d8a3a5b1e6de1e8c86eec6683cef346e jdk8u172-b03
+c3942af7d2fa3c13cf43c49399d36843dd21731f jdk8u172-b04
diff --git a/hotspot/.hgtags b/hotspot/.hgtags
index 7c6f71a..1862911 100644
--- a/hotspot/.hgtags
+++ b/hotspot/.hgtags
@@ -1136,3 +1136,9 @@
 1acd7c1b80241def8fac90f70b0df16356adad47 jdk8u171-b02
 5587cde50bbc2aa031aefb47eaa36b041f5e7c4b jdk8u171-b03
 99ef466523302cfbd00496cf6575a00c8637b884 jdk8u171-b04
+08326a76b14888908523cf2bb1105de63b43544d jdk8u171-b05
+f299cf0b7baea1ae85f139f97adb9ab5499f402a jdk8u172-b00
+d10254debf7c1342416062bf1ba5258f16a8ce00 jdk8u172-b01
+653d9e0cd3f4023675c9eece7f0d563287f1d34f jdk8u172-b02
+771d9e1fbe1ae2ec4d5d937ebcbfd18e9c800098 jdk8u172-b03
+efd7a4e211e8fddf52053d4b033d8d307f356bc3 jdk8u172-b04
diff --git a/hotspot/src/os/bsd/vm/os_bsd.cpp b/hotspot/src/os/bsd/vm/os_bsd.cpp
index 58b5896..fb811915 100644
--- a/hotspot/src/os/bsd/vm/os_bsd.cpp
+++ b/hotspot/src/os/bsd/vm/os_bsd.cpp
@@ -1681,14 +1681,9 @@
 
   dlclose(handle);
 #elif defined(__APPLE__)
-  uint32_t count;
-  uint32_t i;
-
-  count = _dyld_image_count();
-  for (i = 1; i < count; i++) {
-    const char *name = _dyld_get_image_name(i);
-    intptr_t slide = _dyld_get_image_vmaddr_slide(i);
-    st->print_cr(PTR_FORMAT " \t%s", slide, name);
+  for (uint32_t i = 1; i < _dyld_image_count(); i++) {
+    st->print_cr(PTR_FORMAT " \t%s", _dyld_get_image_header(i),
+        _dyld_get_image_name(i));
   }
 #else
   st->print_cr("Error: Cannot print dynamic libraries.");
diff --git a/hotspot/src/share/vm/classfile/classLoaderStats.cpp b/hotspot/src/share/vm/classfile/classLoaderStats.cpp
new file mode 100644
index 0000000..7132c22
--- /dev/null
+++ b/hotspot/src/share/vm/classfile/classLoaderStats.cpp
@@ -0,0 +1,167 @@
+/*
+ * Copyright (c) 2014, 2017, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * 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/classLoaderStats.hpp"
+#include "utilities/globalDefinitions.hpp"
+
+
+class ClassStatsClosure : public KlassClosure {
+public:
+  int _num_classes;
+
+  ClassStatsClosure() :
+    _num_classes(0) {
+  }
+
+  virtual void do_klass(Klass* k) {
+    _num_classes++;
+  }
+};
+
+
+void ClassLoaderStatsClosure::do_cld(ClassLoaderData* cld) {
+  oop cl = cld->class_loader();
+  ClassLoaderStats* cls;
+
+  // The hashtable key is the ClassLoader oop since we want to account
+  // for "real" classes and anonymous classes together
+  ClassLoaderStats** cls_ptr = _stats->get(cl);
+  if (cls_ptr == NULL) {
+    cls = new ClassLoaderStats();
+    _stats->put(cl, cls);
+    _total_loaders++;
+  } else {
+    cls = *cls_ptr;
+  }
+
+  if (!cld->is_anonymous()) {
+    cls->_cld = cld;
+  }
+
+  cls->_class_loader = cl;
+  if (cl != NULL) {
+    cls->_parent = java_lang_ClassLoader::parent(cl);
+    addEmptyParents(cls->_parent);
+  }
+
+  ClassStatsClosure csc;
+  cld->classes_do(&csc);
+  if(cld->is_anonymous()) {
+    cls->_anon_classes_count += csc._num_classes;
+  } else {
+    cls->_classes_count = csc._num_classes;
+  }
+  _total_classes += csc._num_classes;
+
+  Metaspace* ms = cld->metaspace_or_null();
+  if (ms != NULL) {
+    if(cld->is_anonymous()) {
+      cls->_anon_chunk_sz += ms->allocated_chunks_bytes();
+      cls->_anon_block_sz += ms->allocated_blocks_bytes();
+    } else {
+      cls->_chunk_sz = ms->allocated_chunks_bytes();
+      cls->_block_sz = ms->allocated_blocks_bytes();
+    }
+    _total_chunk_sz += ms->allocated_chunks_bytes();
+    _total_block_sz += ms->allocated_blocks_bytes();
+  }
+}
+
+
+// Handles the difference in pointer width on 32 and 64 bit platforms
+#ifdef _LP64
+  #define SPACE "%8s"
+#else
+  #define SPACE "%s"
+#endif
+
+
+bool ClassLoaderStatsClosure::do_entry(oop const& key, ClassLoaderStats* const& cls) {
+  Klass* class_loader_klass = (cls->_class_loader == NULL ? NULL : cls->_class_loader->klass());
+  Klass* parent_klass = (cls->_parent == NULL ? NULL : cls->_parent->klass());
+
+  _out->print(INTPTR_FORMAT "  " INTPTR_FORMAT "  " INTPTR_FORMAT "  " UINTX_FORMAT_W(6) "  " SIZE_FORMAT_W(8) "  " SIZE_FORMAT_W(8) "  ",
+      p2i(class_loader_klass), p2i(parent_klass), p2i(cls->_cld),
+      cls->_classes_count,
+      cls->_chunk_sz, cls->_block_sz);
+  if (class_loader_klass != NULL) {
+    _out->print("%s", class_loader_klass->external_name());
+  } else {
+    _out->print("<boot class loader>");
+  }
+  _out->cr();
+  if (cls->_anon_classes_count > 0) {
+    _out->print_cr(SPACE SPACE SPACE "                                    " UINTX_FORMAT_W(6) "  " SIZE_FORMAT_W(8) "  " SIZE_FORMAT_W(8) "   + unsafe anonymous classes",
+        "", "", "",
+        cls->_anon_classes_count,
+        cls->_anon_chunk_sz, cls->_anon_block_sz);
+  }
+  return true;
+}
+
+
+void ClassLoaderStatsClosure::print() {
+  _out->print_cr("ClassLoader" SPACE " Parent" SPACE "      CLD*" SPACE "       Classes   ChunkSz   BlockSz  Type", "", "", "");
+  _stats->iterate(this);
+  _out->print("Total = " UINTX_FORMAT_W(-6), _total_loaders);
+  _out->print(SPACE SPACE SPACE "                      ", "", "", "");
+  _out->print_cr(UINTX_FORMAT_W(6) "  " SIZE_FORMAT_W(8) "  " SIZE_FORMAT_W(8) "  ",
+      _total_classes,
+      _total_chunk_sz,
+      _total_block_sz);
+  _out->print_cr("ChunkSz: Total size of all allocated metaspace chunks");
+  _out->print_cr("BlockSz: Total size of all allocated metaspace blocks (each chunk has several blocks)");
+}
+
+
+void ClassLoaderStatsClosure::addEmptyParents(oop cl) {
+  while (cl != NULL && java_lang_ClassLoader::loader_data(cl) == NULL) {
+    // This classloader has not loaded any classes
+    ClassLoaderStats** cls_ptr = _stats->get(cl);
+    if (cls_ptr == NULL) {
+      // It does not exist in our table - add it
+      ClassLoaderStats* cls = new ClassLoaderStats();
+      cls->_class_loader = cl;
+      cls->_parent = java_lang_ClassLoader::parent(cl);
+      _stats->put(cl, cls);
+      _total_loaders++;
+    }
+
+    cl = java_lang_ClassLoader::parent(cl);
+  }
+}
+
+
+void ClassLoaderStatsVMOperation::doit() {
+  ClassLoaderStatsClosure clsc (_out);
+  ClassLoaderDataGraph::cld_do(&clsc);
+  clsc.print();
+}
+
+
+void ClassLoaderStatsDCmd::execute(DCmdSource source, TRAPS) {
+  ClassLoaderStatsVMOperation op(output());
+  VMThread::execute(&op);
+}
diff --git a/hotspot/src/share/vm/classfile/classLoaderStats.hpp b/hotspot/src/share/vm/classfile/classLoaderStats.hpp
new file mode 100644
index 0000000..72904c1
--- /dev/null
+++ b/hotspot/src/share/vm/classfile/classLoaderStats.hpp
@@ -0,0 +1,152 @@
+/*
+ * Copyright (c) 2014, 2017, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * 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_CLASSLOADERSTATS_HPP
+#define SHARE_VM_CLASSFILE_CLASSLOADERSTATS_HPP
+
+
+#include "classfile/classLoaderData.hpp"
+#include "oops/klass.hpp"
+#include "oops/oopsHierarchy.hpp"
+#include "runtime/vm_operations.hpp"
+#include "services/diagnosticCommand.hpp"
+#include "utilities/resourceHash.hpp"
+
+
+class ClassLoaderStatsDCmd : public DCmd {
+public:
+  ClassLoaderStatsDCmd(outputStream* output, bool heap) :
+    DCmd(output, heap) {
+  }
+
+  static const char* name() {
+    return "VM.classloader_stats";
+  }
+
+  static const char* description() {
+    return "Print statistics about all ClassLoaders.";
+  }
+
+  static const char* impact() {
+    return "Low";
+  }
+
+  virtual void execute(DCmdSource source, TRAPS);
+
+  static int num_arguments() {
+    return 0;
+  }
+
+  static const JavaPermission permission() {
+    JavaPermission p = {"java.lang.management.ManagementPermission",
+                        "monitor", NULL};
+    return p;
+  }
+};
+
+
+class ClassLoaderStats : public ResourceObj {
+public:
+  ClassLoaderData*  _cld;
+  oop               _class_loader;
+  oop               _parent;
+
+  size_t            _chunk_sz;
+  size_t            _block_sz;
+  uintx             _classes_count;
+
+  size_t            _anon_chunk_sz;
+  size_t            _anon_block_sz;
+  uintx             _anon_classes_count;
+
+  ClassLoaderStats() :
+    _cld(0),
+    _class_loader(0),
+    _parent(0),
+    _chunk_sz(0),
+    _block_sz(0),
+    _classes_count(0),
+    _anon_block_sz(0),
+    _anon_chunk_sz(0),
+    _anon_classes_count(0) {
+  }
+};
+
+
+class ClassLoaderStatsClosure : public CLDClosure {
+protected:
+  static bool oop_equals(oop const& s1, oop const& s2) {
+    return s1 == s2;
+  }
+
+  static unsigned oop_hash(oop const& s1) {
+    unsigned hash = (unsigned)((uintptr_t)&s1);
+    return hash ^ (hash >> LogMinObjAlignment);
+  }
+
+  typedef ResourceHashtable<oop, ClassLoaderStats*,
+      ClassLoaderStatsClosure::oop_hash, ClassLoaderStatsClosure::oop_equals> StatsTable;
+
+  outputStream* _out;
+  StatsTable* _stats;
+  uintx   _total_loaders;
+  uintx   _total_classes;
+  size_t  _total_chunk_sz;
+  size_t  _total_block_sz;
+
+public:
+  ClassLoaderStatsClosure(outputStream* out) :
+    _out(out),
+    _total_loaders(0),
+    _total_block_sz(0),
+    _total_chunk_sz(0),
+    _total_classes(0),
+    _stats(new StatsTable()) {
+  }
+
+  virtual void do_cld(ClassLoaderData* cld);
+  virtual bool do_entry(oop const& key, ClassLoaderStats* const& cls);
+  void print();
+
+private:
+  void addEmptyParents(oop cl);
+};
+
+
+class ClassLoaderStatsVMOperation : public VM_Operation {
+  outputStream* _out;
+
+public:
+  ClassLoaderStatsVMOperation(outputStream* out) :
+    _out(out) {
+  }
+
+  VMOp_Type type() const {
+    return VMOp_ClassLoaderStatsOperation;
+  }
+
+  void doit();
+};
+
+#endif // SHARE_VM_CLASSFILE_CLASSLOADERSTATS_HPP
diff --git a/hotspot/src/share/vm/classfile/vmSymbols.hpp b/hotspot/src/share/vm/classfile/vmSymbols.hpp
index b531b3c..90ffcf9 100644
--- a/hotspot/src/share/vm/classfile/vmSymbols.hpp
+++ b/hotspot/src/share/vm/classfile/vmSymbols.hpp
@@ -573,6 +573,11 @@
   template(java_lang_management_ThreadInfo_constructor_signature, "(Ljava/lang/Thread;ILjava/lang/Object;Ljava/lang/Thread;JJJJ[Ljava/lang/StackTraceElement;)V") \
   template(java_lang_management_ThreadInfo_with_locks_constructor_signature, "(Ljava/lang/Thread;ILjava/lang/Object;Ljava/lang/Thread;JJJJ[Ljava/lang/StackTraceElement;[Ljava/lang/Object;[I[Ljava/lang/Object;)V") \
   template(long_long_long_long_void_signature,         "(JJJJ)V")                                                 \
+  template(finalizer_histogram_klass,                  "java/lang/ref/FinalizerHistogram")                        \
+  template(void_finalizer_histogram_entry_array_signature,  "()[Ljava/lang/ref/FinalizerHistogram$Entry;")                        \
+  template(get_finalizer_histogram_name,               "getFinalizerHistogram")                                   \
+  template(finalizer_histogram_entry_name_field,       "className")                                               \
+  template(finalizer_histogram_entry_count_field,      "instanceCount")                                           \
                                                                                                                   \
   template(java_lang_management_MemoryPoolMXBean,      "java/lang/management/MemoryPoolMXBean")                   \
   template(java_lang_management_MemoryManagerMXBean,   "java/lang/management/MemoryManagerMXBean")                \
diff --git a/hotspot/src/share/vm/gc_implementation/g1/heapRegionRemSet.cpp b/hotspot/src/share/vm/gc_implementation/g1/heapRegionRemSet.cpp
index 662f4f1..cb3e955 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/heapRegionRemSet.cpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/heapRegionRemSet.cpp
@@ -514,7 +514,15 @@
 
       PerRegionTable* first_prt = _fine_grain_regions[ind];
       prt->set_collision_list_next(first_prt);
-      _fine_grain_regions[ind] = prt;
+      // The assignment into _fine_grain_regions allows the prt to
+      // start being used concurrently. In addition to
+      // collision_list_next which must be visible (else concurrent
+      // parsing of the list, if any, may fail to see other entries),
+      // the content of the prt must be visible (else for instance
+      // some mark bits may not yet seem cleared or a 'later' update
+      // performed by a concurrent thread could be undone when the
+      // zeroing becomes visible). This requires store ordering.
+      OrderAccess::release_store_ptr((volatile PerRegionTable*)&_fine_grain_regions[ind], prt);
       _n_fine_entries++;
 
       if (G1HRRSUseSparseTable) {
diff --git a/hotspot/src/share/vm/memory/metaspace.cpp b/hotspot/src/share/vm/memory/metaspace.cpp
index f80d7b3..764b425 100644
--- a/hotspot/src/share/vm/memory/metaspace.cpp
+++ b/hotspot/src/share/vm/memory/metaspace.cpp
@@ -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
@@ -154,7 +154,7 @@
 
   // Map a size to a list index assuming that there are lists
   // for special, small, medium, and humongous chunks.
-  static ChunkIndex list_index(size_t size);
+  ChunkIndex list_index(size_t size);
 
   // Remove the chunk from its freelist.  It is
   // expected to be on one of the _free_chunks[] lists.
@@ -531,9 +531,8 @@
 
   size_t free_bytes();
 
-  Metachunk* get_new_chunk(size_t word_size,
-                           size_t grow_chunks_by_words,
-                           size_t medium_chunk_bunch);
+  Metachunk* get_new_chunk(size_t chunk_word_size,
+                           size_t suggested_commit_granularity);
 
   bool expand_node_by(VirtualSpaceNode* node,
                       size_t min_words,
@@ -687,19 +686,27 @@
     MediumChunkMultiple = 4
   };
 
-  bool is_class() { return _mdtype == Metaspace::ClassType; }
+  static size_t specialized_chunk_size(bool is_class) { return is_class ? ClassSpecializedChunk : SpecializedChunk; }
+  static size_t small_chunk_size(bool is_class)       { return is_class ? ClassSmallChunk : SmallChunk; }
+  static size_t medium_chunk_size(bool is_class)      { return is_class ? ClassMediumChunk : MediumChunk; }
+
+  static size_t smallest_chunk_size(bool is_class)    { return specialized_chunk_size(is_class); }
 
   // Accessors
-  size_t specialized_chunk_size() { return (size_t) is_class() ? ClassSpecializedChunk : SpecializedChunk; }
-  size_t small_chunk_size()       { return (size_t) is_class() ? ClassSmallChunk : SmallChunk; }
-  size_t medium_chunk_size()      { return (size_t) is_class() ? ClassMediumChunk : MediumChunk; }
-  size_t medium_chunk_bunch()     { return medium_chunk_size() * MediumChunkMultiple; }
+  bool is_class() const { return _mdtype == Metaspace::ClassType; }
 
-  size_t smallest_chunk_size()  { return specialized_chunk_size(); }
+  size_t specialized_chunk_size() const { return specialized_chunk_size(is_class()); }
+  size_t small_chunk_size()       const { return small_chunk_size(is_class()); }
+  size_t medium_chunk_size()      const { return medium_chunk_size(is_class()); }
+
+  size_t smallest_chunk_size()    const { return smallest_chunk_size(is_class()); }
+
+  size_t medium_chunk_bunch()     const { return medium_chunk_size() * MediumChunkMultiple; }
 
   size_t allocated_blocks_words() const { return _allocated_blocks_words; }
   size_t allocated_blocks_bytes() const { return _allocated_blocks_words * BytesPerWord; }
   size_t allocated_chunks_words() const { return _allocated_chunks_words; }
+  size_t allocated_chunks_bytes() const { return _allocated_chunks_words * BytesPerWord; }
   size_t allocated_chunks_count() const { return _allocated_chunks_count; }
 
   bool is_humongous(size_t word_size) { return word_size > medium_chunk_size(); }
@@ -718,10 +725,13 @@
   // decremented for all the Metachunks in-use by this SpaceManager.
   void dec_total_from_size_metrics();
 
-  // Set the sizes for the initial chunks.
-  void get_initial_chunk_sizes(Metaspace::MetaspaceType type,
-                               size_t* chunk_word_size,
-                               size_t* class_chunk_word_size);
+  // Adjust the initial chunk size to match one of the fixed chunk list sizes,
+  // or return the unadjusted size if the requested size is humongous.
+  static size_t adjust_initial_chunk_size(size_t requested, bool is_class_space);
+  size_t adjust_initial_chunk_size(size_t requested) const;
+
+  // Get the initial chunks size for this metaspace type.
+  size_t get_initial_chunk_size(Metaspace::MetaspaceType type) const;
 
   size_t sum_capacity_in_chunks_in_use() const;
   size_t sum_used_in_chunks_in_use() const;
@@ -732,7 +742,7 @@
   size_t sum_count_in_chunks_in_use();
   size_t sum_count_in_chunks_in_use(ChunkIndex i);
 
-  Metachunk* get_new_chunk(size_t word_size, size_t grow_chunks_by_words);
+  Metachunk* get_new_chunk(size_t chunk_word_size);
 
   // Block allocation and deallocation.
   // Allocates a block from the current chunk
@@ -1200,7 +1210,7 @@
 }
 
 size_t VirtualSpaceList::free_bytes() {
-  return virtual_space_list()->free_words_in_vs() * BytesPerWord;
+  return current_virtual_space()->free_words_in_vs() * BytesPerWord;
 }
 
 // Allocate another meta virtual space and add it to the list.
@@ -1319,12 +1329,10 @@
   return false;
 }
 
-Metachunk* VirtualSpaceList::get_new_chunk(size_t word_size,
-                                           size_t grow_chunks_by_words,
-                                           size_t medium_chunk_bunch) {
+Metachunk* VirtualSpaceList::get_new_chunk(size_t chunk_word_size, size_t suggested_commit_granularity) {
 
   // Allocate a chunk out of the current virtual space.
-  Metachunk* next = current_virtual_space()->get_chunk_vs(grow_chunks_by_words);
+  Metachunk* next = current_virtual_space()->get_chunk_vs(chunk_word_size);
 
   if (next != NULL) {
     return next;
@@ -1333,8 +1341,8 @@
   // The expand amount is currently only determined by the requested sizes
   // and not how much committed memory is left in the current virtual space.
 
-  size_t min_word_size       = align_size_up(grow_chunks_by_words, Metaspace::commit_alignment_words());
-  size_t preferred_word_size = align_size_up(medium_chunk_bunch,   Metaspace::commit_alignment_words());
+  size_t min_word_size       = align_size_up(chunk_word_size,              Metaspace::commit_alignment_words());
+  size_t preferred_word_size = align_size_up(suggested_commit_granularity, Metaspace::commit_alignment_words());
   if (min_word_size >= preferred_word_size) {
     // Can happen when humongous chunks are allocated.
     preferred_word_size = min_word_size;
@@ -1342,7 +1350,7 @@
 
   bool expanded = expand_by(min_word_size, preferred_word_size);
   if (expanded) {
-    next = current_virtual_space()->get_chunk_vs(grow_chunks_by_words);
+    next = current_virtual_space()->get_chunk_vs(chunk_word_size);
     assert(next != NULL, "The allocation was expected to succeed after the expansion");
   }
 
@@ -1744,7 +1752,11 @@
   st->print_cr("Sum free chunk total " SIZE_FORMAT "  count " SIZE_FORMAT,
                 sum_free_chunks(), sum_free_chunks_count());
 }
+
 ChunkList* ChunkManager::free_chunks(ChunkIndex index) {
+  assert(index == SpecializedIndex || index == SmallIndex || index == MediumIndex,
+         err_msg("Bad index: %d", (int)index));
+
   return &_free_chunks[index];
 }
 
@@ -1856,7 +1868,7 @@
   }
 
   assert((word_size <= chunk->word_size()) ||
-         list_index(chunk->word_size() == HumongousIndex),
+         (list_index(chunk->word_size()) == HumongousIndex),
          "Non-humongous variable sized chunk");
   if (TraceMetadataChunkAllocation) {
     size_t list_count;
@@ -1883,36 +1895,58 @@
 
 // SpaceManager methods
 
-void SpaceManager::get_initial_chunk_sizes(Metaspace::MetaspaceType type,
-                                           size_t* chunk_word_size,
-                                           size_t* class_chunk_word_size) {
-  switch (type) {
-  case Metaspace::BootMetaspaceType:
-    *chunk_word_size = Metaspace::first_chunk_word_size();
-    *class_chunk_word_size = Metaspace::first_class_chunk_word_size();
-    break;
-  case Metaspace::ROMetaspaceType:
-    *chunk_word_size = SharedReadOnlySize / wordSize;
-    *class_chunk_word_size = ClassSpecializedChunk;
-    break;
-  case Metaspace::ReadWriteMetaspaceType:
-    *chunk_word_size = SharedReadWriteSize / wordSize;
-    *class_chunk_word_size = ClassSpecializedChunk;
-    break;
-  case Metaspace::AnonymousMetaspaceType:
-  case Metaspace::ReflectionMetaspaceType:
-    *chunk_word_size = SpecializedChunk;
-    *class_chunk_word_size = ClassSpecializedChunk;
-    break;
-  default:
-    *chunk_word_size = SmallChunk;
-    *class_chunk_word_size = ClassSmallChunk;
-    break;
+size_t SpaceManager::adjust_initial_chunk_size(size_t requested, bool is_class_space) {
+  size_t chunk_sizes[] = {
+      specialized_chunk_size(is_class_space),
+      small_chunk_size(is_class_space),
+      medium_chunk_size(is_class_space)
+  };
+
+  // Adjust up to one of the fixed chunk sizes ...
+  for (size_t i = 0; i < ARRAY_SIZE(chunk_sizes); i++) {
+    if (requested <= chunk_sizes[i]) {
+      return chunk_sizes[i];
+    }
   }
-  assert(*chunk_word_size != 0 && *class_chunk_word_size != 0,
-    err_msg("Initial chunks sizes bad: data  " SIZE_FORMAT
-            " class " SIZE_FORMAT,
-            *chunk_word_size, *class_chunk_word_size));
+
+  // ... or return the size as a humongous chunk.
+  return requested;
+}
+
+size_t SpaceManager::adjust_initial_chunk_size(size_t requested) const {
+  return adjust_initial_chunk_size(requested, is_class());
+}
+
+size_t SpaceManager::get_initial_chunk_size(Metaspace::MetaspaceType type) const {
+  size_t requested;
+
+  if (is_class()) {
+    switch (type) {
+    case Metaspace::BootMetaspaceType:       requested = Metaspace::first_class_chunk_word_size(); break;
+    case Metaspace::ROMetaspaceType:         requested = ClassSpecializedChunk; break;
+    case Metaspace::ReadWriteMetaspaceType:  requested = ClassSpecializedChunk; break;
+    case Metaspace::AnonymousMetaspaceType:  requested = ClassSpecializedChunk; break;
+    case Metaspace::ReflectionMetaspaceType: requested = ClassSpecializedChunk; break;
+    default:                                 requested = ClassSmallChunk; break;
+    }
+  } else {
+    switch (type) {
+    case Metaspace::BootMetaspaceType:       requested = Metaspace::first_chunk_word_size(); break;
+    case Metaspace::ROMetaspaceType:         requested = SharedReadOnlySize / wordSize; break;
+    case Metaspace::ReadWriteMetaspaceType:  requested = SharedReadWriteSize / wordSize; break;
+    case Metaspace::AnonymousMetaspaceType:  requested = SpecializedChunk; break;
+    case Metaspace::ReflectionMetaspaceType: requested = SpecializedChunk; break;
+    default:                                 requested = SmallChunk; break;
+    }
+  }
+
+  // Adjust to one of the fixed chunk sizes (unless humongous)
+  const size_t adjusted = adjust_initial_chunk_size(requested);
+
+  assert(adjusted != 0, err_msg("Incorrect initial chunk size. Requested: "
+         SIZE_FORMAT " adjusted: " SIZE_FORMAT, requested, adjusted));
+
+  return adjusted;
 }
 
 size_t SpaceManager::sum_free_in_chunks_in_use() const {
@@ -2102,8 +2136,8 @@
   }
 
   // Get another chunk out of the virtual space
-  size_t grow_chunks_by_words = calc_chunk_size(word_size);
-  Metachunk* next = get_new_chunk(word_size, grow_chunks_by_words);
+  size_t chunk_word_size = calc_chunk_size(word_size);
+  Metachunk* next = get_new_chunk(chunk_word_size);
 
   MetaWord* mem = NULL;
 
@@ -2328,22 +2362,18 @@
 }
 
 ChunkIndex ChunkManager::list_index(size_t size) {
-  switch (size) {
-    case SpecializedChunk:
-      assert(SpecializedChunk == ClassSpecializedChunk,
-             "Need branch for ClassSpecializedChunk");
-      return SpecializedIndex;
-    case SmallChunk:
-    case ClassSmallChunk:
-      return SmallIndex;
-    case MediumChunk:
-    case ClassMediumChunk:
-      return MediumIndex;
-    default:
-      assert(size > MediumChunk || size > ClassMediumChunk,
-             "Not a humongous chunk");
-      return HumongousIndex;
+  if (free_chunks(SpecializedIndex)->size() == size) {
+    return SpecializedIndex;
   }
+  if (free_chunks(SmallIndex)->size() == size) {
+    return SmallIndex;
+  }
+  if (free_chunks(MediumIndex)->size() == size) {
+    return MediumIndex;
+  }
+
+  assert(size > free_chunks(MediumIndex)->size(), "Not a humongous chunk");
+  return HumongousIndex;
 }
 
 void SpaceManager::deallocate(MetaWord* p, size_t word_size) {
@@ -2365,7 +2395,7 @@
 
   // Find the correct list and and set the current
   // chunk for that list.
-  ChunkIndex index = ChunkManager::list_index(new_chunk->word_size());
+  ChunkIndex index = chunk_manager()->list_index(new_chunk->word_size());
 
   if (index != HumongousIndex) {
     retire_current_chunk();
@@ -2412,14 +2442,12 @@
   }
 }
 
-Metachunk* SpaceManager::get_new_chunk(size_t word_size,
-                                       size_t grow_chunks_by_words) {
+Metachunk* SpaceManager::get_new_chunk(size_t chunk_word_size) {
   // Get a chunk from the chunk freelist
-  Metachunk* next = chunk_manager()->chunk_freelist_allocate(grow_chunks_by_words);
+  Metachunk* next = chunk_manager()->chunk_freelist_allocate(chunk_word_size);
 
   if (next == NULL) {
-    next = vs_list()->get_new_chunk(word_size,
-                                    grow_chunks_by_words,
+    next = vs_list()->get_new_chunk(chunk_word_size,
                                     medium_chunk_bunch());
   }
 
@@ -3085,7 +3113,7 @@
          err_msg(SIZE_FORMAT " != " UINTX_FORMAT, rs.size(), CompressedClassSpaceSize));
   assert(using_class_space(), "Must be using class space");
   _class_space_list = new VirtualSpaceList(rs);
-  _chunk_manager_class = new ChunkManager(SpecializedChunk, ClassSmallChunk, ClassMediumChunk);
+  _chunk_manager_class = new ChunkManager(ClassSpecializedChunk, ClassSmallChunk, ClassMediumChunk);
 
   if (!_class_space_list->initialization_succeeded()) {
     vm_exit_during_initialization("Failed to setup compressed class space virtual space list.");
@@ -3286,66 +3314,62 @@
   MetaspaceGC::post_initialize();
 }
 
-Metachunk* Metaspace::get_initialization_chunk(MetadataType mdtype,
-                                               size_t chunk_word_size,
-                                               size_t chunk_bunch) {
+void Metaspace::initialize_first_chunk(MetaspaceType type, MetadataType mdtype) {
+  Metachunk* chunk = get_initialization_chunk(type, mdtype);
+  if (chunk != NULL) {
+    // Add to this manager's list of chunks in use and current_chunk().
+    get_space_manager(mdtype)->add_chunk(chunk, true);
+  }
+}
+
+Metachunk* Metaspace::get_initialization_chunk(MetaspaceType type, MetadataType mdtype) {
+  size_t chunk_word_size = get_space_manager(mdtype)->get_initial_chunk_size(type);
+
   // Get a chunk from the chunk freelist
   Metachunk* chunk = get_chunk_manager(mdtype)->chunk_freelist_allocate(chunk_word_size);
-  if (chunk != NULL) {
-    return chunk;
+
+  if (chunk == NULL) {
+    chunk = get_space_list(mdtype)->get_new_chunk(chunk_word_size,
+                                                  get_space_manager(mdtype)->medium_chunk_bunch());
   }
 
-  return get_space_list(mdtype)->get_new_chunk(chunk_word_size, chunk_word_size, chunk_bunch);
+  // For dumping shared archive, report error if allocation has failed.
+  if (DumpSharedSpaces && chunk == NULL) {
+    report_insufficient_metaspace(MetaspaceAux::committed_bytes() + chunk_word_size * BytesPerWord);
+  }
+
+  return chunk;
+}
+
+void Metaspace::verify_global_initialization() {
+  assert(space_list() != NULL, "Metadata VirtualSpaceList has not been initialized");
+  assert(chunk_manager_metadata() != NULL, "Metadata ChunkManager has not been initialized");
+
+  if (using_class_space()) {
+    assert(class_space_list() != NULL, "Class VirtualSpaceList has not been initialized");
+    assert(chunk_manager_class() != NULL, "Class ChunkManager has not been initialized");
+  }
 }
 
 void Metaspace::initialize(Mutex* lock, MetaspaceType type) {
+  verify_global_initialization();
 
-  assert(space_list() != NULL,
-    "Metadata VirtualSpaceList has not been initialized");
-  assert(chunk_manager_metadata() != NULL,
-    "Metadata ChunkManager has not been initialized");
-
+  // Allocate SpaceManager for metadata objects.
   _vsm = new SpaceManager(NonClassType, lock);
-  if (_vsm == NULL) {
-    return;
-  }
-  size_t word_size;
-  size_t class_word_size;
-  vsm()->get_initial_chunk_sizes(type, &word_size, &class_word_size);
 
   if (using_class_space()) {
-  assert(class_space_list() != NULL,
-    "Class VirtualSpaceList has not been initialized");
-  assert(chunk_manager_class() != NULL,
-    "Class ChunkManager has not been initialized");
-
     // Allocate SpaceManager for classes.
     _class_vsm = new SpaceManager(ClassType, lock);
-    if (_class_vsm == NULL) {
-      return;
-    }
   }
 
   MutexLockerEx cl(SpaceManager::expand_lock(), Mutex::_no_safepoint_check_flag);
 
   // Allocate chunk for metadata objects
-  Metachunk* new_chunk = get_initialization_chunk(NonClassType,
-                                                  word_size,
-                                                  vsm()->medium_chunk_bunch());
-  assert(!DumpSharedSpaces || new_chunk != NULL, "should have enough space for both chunks");
-  if (new_chunk != NULL) {
-    // Add to this manager's list of chunks in use and current_chunk().
-    vsm()->add_chunk(new_chunk, true);
-  }
+  initialize_first_chunk(type, NonClassType);
 
   // Allocate chunk for class metadata objects
   if (using_class_space()) {
-    Metachunk* class_chunk = get_initialization_chunk(ClassType,
-                                                      class_word_size,
-                                                      class_vsm()->medium_chunk_bunch());
-    if (class_chunk != NULL) {
-      class_vsm()->add_chunk(class_chunk, true);
-    }
+    initialize_first_chunk(type, ClassType);
   }
 
   _alloc_record_head = NULL;
@@ -3440,6 +3464,16 @@
   return capacity_words_slow(mdtype) * BytesPerWord;
 }
 
+size_t Metaspace::allocated_blocks_bytes() const {
+  return vsm()->allocated_blocks_bytes() +
+      (using_class_space() ? class_vsm()->allocated_blocks_bytes() : 0);
+}
+
+size_t Metaspace::allocated_chunks_bytes() const {
+  return vsm()->allocated_chunks_bytes() +
+      (using_class_space() ? class_vsm()->allocated_chunks_bytes() : 0);
+}
+
 void Metaspace::deallocate(MetaWord* ptr, size_t word_size, bool is_class) {
   if (SafepointSynchronize::is_at_safepoint()) {
     if (DumpSharedSpaces && PrintSharedSpaces) {
@@ -3772,7 +3806,7 @@
     // vm_allocation_granularity aligned on Windows.
     size_t large_size = (size_t)(2*256*K + (os::vm_page_size()/BytesPerWord));
     large_size += (os::vm_page_size()/BytesPerWord);
-    vs_list->get_new_chunk(large_size, large_size, 0);
+    vs_list->get_new_chunk(large_size, 0);
   }
 
   static void test() {
@@ -3947,4 +3981,90 @@
   TestVirtualSpaceNodeTest::test();
   TestVirtualSpaceNodeTest::test_is_available();
 }
+
+// The following test is placed here instead of a gtest / unittest file
+// because the ChunkManager class is only available in this file.
+class SpaceManagerTest : AllStatic {
+  friend void SpaceManager_test_adjust_initial_chunk_size();
+
+  static void test_adjust_initial_chunk_size(bool is_class) {
+    const size_t smallest = SpaceManager::smallest_chunk_size(is_class);
+    const size_t normal   = SpaceManager::small_chunk_size(is_class);
+    const size_t medium   = SpaceManager::medium_chunk_size(is_class);
+
+#define test_adjust_initial_chunk_size(value, expected, is_class_value)          \
+    do {                                                                         \
+      size_t v = value;                                                          \
+      size_t e = expected;                                                       \
+      assert(SpaceManager::adjust_initial_chunk_size(v, (is_class_value)) == e,  \
+             err_msg("Expected: " SIZE_FORMAT " got: " SIZE_FORMAT, e, v));      \
+    } while (0)
+
+    // Smallest (specialized)
+    test_adjust_initial_chunk_size(1,            smallest, is_class);
+    test_adjust_initial_chunk_size(smallest - 1, smallest, is_class);
+    test_adjust_initial_chunk_size(smallest,     smallest, is_class);
+
+    // Small
+    test_adjust_initial_chunk_size(smallest + 1, normal, is_class);
+    test_adjust_initial_chunk_size(normal - 1,   normal, is_class);
+    test_adjust_initial_chunk_size(normal,       normal, is_class);
+
+    // Medium
+    test_adjust_initial_chunk_size(normal + 1, medium, is_class);
+    test_adjust_initial_chunk_size(medium - 1, medium, is_class);
+    test_adjust_initial_chunk_size(medium,     medium, is_class);
+
+    // Humongous
+    test_adjust_initial_chunk_size(medium + 1, medium + 1, is_class);
+
+#undef test_adjust_initial_chunk_size
+  }
+
+  static void test_adjust_initial_chunk_size() {
+    test_adjust_initial_chunk_size(false);
+    test_adjust_initial_chunk_size(true);
+  }
+};
+
+void SpaceManager_test_adjust_initial_chunk_size() {
+  SpaceManagerTest::test_adjust_initial_chunk_size();
+}
+
+// The following test is placed here instead of a gtest / unittest file
+// because the ChunkManager class is only available in this file.
+void ChunkManager_test_list_index() {
+  ChunkManager manager(ClassSpecializedChunk, ClassSmallChunk, ClassMediumChunk);
+
+  // Test previous bug where a query for a humongous class metachunk,
+  // incorrectly matched the non-class medium metachunk size.
+  {
+    assert(MediumChunk > ClassMediumChunk, "Precondition for test");
+
+    ChunkIndex index = manager.list_index(MediumChunk);
+
+    assert(index == HumongousIndex,
+           err_msg("Requested size is larger than ClassMediumChunk,"
+           " so should return HumongousIndex. Got index: %d", (int)index));
+  }
+
+  // Check the specified sizes as well.
+  {
+    ChunkIndex index = manager.list_index(ClassSpecializedChunk);
+    assert(index == SpecializedIndex, err_msg("Wrong index returned. Got index: %d", (int)index));
+  }
+  {
+    ChunkIndex index = manager.list_index(ClassSmallChunk);
+    assert(index == SmallIndex, err_msg("Wrong index returned. Got index: %d", (int)index));
+  }
+  {
+    ChunkIndex index = manager.list_index(ClassMediumChunk);
+    assert(index == MediumIndex, err_msg("Wrong index returned. Got index: %d", (int)index));
+  }
+  {
+    ChunkIndex index = manager.list_index(ClassMediumChunk + 1);
+    assert(index == HumongousIndex, err_msg("Wrong index returned. Got index: %d", (int)index));
+  }
+}
+
 #endif
diff --git a/hotspot/src/share/vm/memory/metaspace.hpp b/hotspot/src/share/vm/memory/metaspace.hpp
index 2026420..051f35b 100644
--- a/hotspot/src/share/vm/memory/metaspace.hpp
+++ b/hotspot/src/share/vm/memory/metaspace.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
+ * 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
@@ -104,14 +104,15 @@
   };
 
  private:
+  static void verify_global_initialization();
+
   void initialize(Mutex* lock, MetaspaceType type);
 
-  // Get the first chunk for a Metaspace.  Used for
+  // Initialize the first chunk for a Metaspace.  Used for
   // special cases such as the boot class loader, reflection
   // class loader and anonymous class loader.
-  Metachunk* get_initialization_chunk(MetadataType mdtype,
-                                      size_t chunk_word_size,
-                                      size_t chunk_bunch);
+  void initialize_first_chunk(MetaspaceType type, MetadataType mdtype);
+  Metachunk* get_initialization_chunk(MetaspaceType type, MetadataType mdtype);
 
   // Align up the word size to the allocation word size
   static size_t align_word_size_up(size_t);
@@ -138,6 +139,10 @@
 
   SpaceManager* _class_vsm;
   SpaceManager* class_vsm() const { return _class_vsm; }
+  SpaceManager* get_space_manager(MetadataType mdtype) {
+    assert(mdtype != MetadataTypeCount, "MetadaTypeCount can't be used as mdtype");
+    return mdtype == ClassType ? class_vsm() : vsm();
+  }
 
   // Allocate space for metadata of type mdtype. This is space
   // within a Metachunk and is used by
@@ -227,6 +232,9 @@
   size_t used_bytes_slow(MetadataType mdtype) const;
   size_t capacity_bytes_slow(MetadataType mdtype) const;
 
+  size_t allocated_blocks_bytes() const;
+  size_t allocated_chunks_bytes() const;
+
   static MetaWord* allocate(ClassLoaderData* loader_data, size_t word_size,
                             bool read_only, MetaspaceObj::Type type, TRAPS);
   void deallocate(MetaWord* ptr, size_t byte_size, bool is_class);
diff --git a/hotspot/src/share/vm/memory/resourceArea.cpp b/hotspot/src/share/vm/memory/resourceArea.cpp
index 767e45e..3995e63 100644
--- a/hotspot/src/share/vm/memory/resourceArea.cpp
+++ b/hotspot/src/share/vm/memory/resourceArea.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,6 +27,15 @@
 #include "memory/resourceArea.hpp"
 #include "runtime/mutexLocker.hpp"
 #include "runtime/thread.inline.hpp"
+#include "services/memTracker.hpp"
+
+void ResourceArea::bias_to(MEMFLAGS new_flags) {
+  if (new_flags != _flags) {
+    MemTracker::record_arena_free(_flags);
+    MemTracker::record_new_arena(new_flags);
+    _flags = new_flags;
+  }
+}
 
 //------------------------------ResourceMark-----------------------------------
 debug_only(int ResourceArea::_warned;)      // to suppress multiple warnings
diff --git a/hotspot/src/share/vm/memory/resourceArea.hpp b/hotspot/src/share/vm/memory/resourceArea.hpp
index 567b5fc..7ffe641 100644
--- a/hotspot/src/share/vm/memory/resourceArea.hpp
+++ b/hotspot/src/share/vm/memory/resourceArea.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -49,11 +49,11 @@
   debug_only(static int _warned;)       // to suppress multiple warnings
 
 public:
-  ResourceArea() : Arena(mtThread) {
+  ResourceArea(MEMFLAGS flags = mtThread) : Arena(flags) {
     debug_only(_nesting = 0;)
   }
 
-  ResourceArea(size_t init_size) : Arena(mtThread, init_size) {
+  ResourceArea(size_t init_size, MEMFLAGS flags = mtThread) : Arena(flags, init_size) {
     debug_only(_nesting = 0;);
   }
 
@@ -70,7 +70,11 @@
     return (char*)Amalloc(size, alloc_failmode);
   }
 
-  debug_only(int nesting() const { return _nesting; });
+  // Bias this resource area to specific memory type
+  // (by default, ResourceArea is tagged as mtThread, per-thread general purpose storage)
+  void bias_to(MEMFLAGS flags);
+
+  debug_only(int nesting() const { return _nesting; })
 };
 
 
diff --git a/hotspot/src/share/vm/opto/chaitin.cpp b/hotspot/src/share/vm/opto/chaitin.cpp
index 5930650..29a0a39 100644
--- a/hotspot/src/share/vm/opto/chaitin.cpp
+++ b/hotspot/src/share/vm/opto/chaitin.cpp
@@ -338,8 +338,8 @@
   _alternate = 0;
   _matcher._allocation_started = true;
 
-  ResourceArea split_arena;     // Arena for Split local resources
-  ResourceArea live_arena;      // Arena for liveness & IFG info
+  ResourceArea split_arena(mtCompiler);     // Arena for Split local resources
+  ResourceArea live_arena(mtCompiler);      // Arena for liveness & IFG info
   ResourceMark rm(&live_arena);
 
   // Need live-ness for the IFG; need the IFG for coalescing.  If the
diff --git a/hotspot/src/share/vm/opto/loopopts.cpp b/hotspot/src/share/vm/opto/loopopts.cpp
index e19f35a..0452a23 100644
--- a/hotspot/src/share/vm/opto/loopopts.cpp
+++ b/hotspot/src/share/vm/opto/loopopts.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -309,6 +309,7 @@
       }
       return NULL;
     }
+    assert(m->is_Phi() || is_dominator(get_ctrl(m), n_ctrl), "m has strange control");
   }
 
   return n_ctrl;
@@ -609,6 +610,7 @@
   // Now replace all Phis with CMOV's
   Node *cmov_ctrl = iff->in(0);
   uint flip = (lp->Opcode() == Op_IfTrue);
+  Node_List wq;
   while (1) {
     PhiNode* phi = NULL;
     for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) {
@@ -623,17 +625,21 @@
     if (PrintOpto && VerifyLoopOptimizations) tty->print_cr("CMOV");
 #endif
     // Move speculative ops
-    for (uint j = 1; j < region->req(); j++) {
-      Node *proj = region->in(j);
-      Node *inp = phi->in(j);
-      if (get_ctrl(inp) == proj) { // Found local op
+    wq.push(phi);
+    while (wq.size() > 0) {
+      Node *n = wq.pop();
+      for (uint j = 1; j < n->req(); j++) {
+        Node* m = n->in(j);
+        if (m != NULL && !is_dominator(get_ctrl(m), cmov_ctrl)) {
 #ifndef PRODUCT
-        if (PrintOpto && VerifyLoopOptimizations) {
-          tty->print("  speculate: ");
-          inp->dump();
-        }
+          if (PrintOpto && VerifyLoopOptimizations) {
+            tty->print("  speculate: ");
+            m->dump();
+          }
 #endif
-        set_ctrl(inp, cmov_ctrl);
+          set_ctrl(m, cmov_ctrl);
+          wq.push(m);
+        }
       }
     }
     Node *cmov = CMoveNode::make( C, cmov_ctrl, iff->in(1), phi->in(1+flip), phi->in(2-flip), _igvn.type(phi) );
diff --git a/hotspot/src/share/vm/opto/matcher.cpp b/hotspot/src/share/vm/opto/matcher.cpp
index d6ee92f..47a2227 100644
--- a/hotspot/src/share/vm/opto/matcher.cpp
+++ b/hotspot/src/share/vm/opto/matcher.cpp
@@ -79,7 +79,7 @@
   _register_save_type(register_save_type),
   _ruleName(ruleName),
   _allocation_started(false),
-  _states_arena(Chunk::medium_size),
+  _states_arena(Chunk::medium_size, mtCompiler),
   _visited(&_states_arena),
   _shared(&_states_arena),
   _dontcare(&_states_arena) {
diff --git a/hotspot/src/share/vm/prims/jni.cpp b/hotspot/src/share/vm/prims/jni.cpp
index 0077fab..6a6ab93 100644
--- a/hotspot/src/share/vm/prims/jni.cpp
+++ b/hotspot/src/share/vm/prims/jni.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * Copyright (c) 2012 Red Hat, Inc.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
@@ -5093,6 +5093,7 @@
 void TestReserveMemorySpecial_test();
 void TestVirtualSpace_test();
 void TestMetaspaceAux_test();
+void SpaceManager_test_adjust_initial_chunk_size();
 void TestMetachunk_test();
 void TestVirtualSpaceNode_test();
 void TestNewSize_test();
@@ -5105,6 +5106,7 @@
 void TestBufferingOopClosure_test();
 void TestCodeCacheRemSet_test();
 void FreeRegionList_test();
+void ChunkManager_test_list_index();
 #endif
 
 void execute_internal_vm_tests() {
@@ -5137,6 +5139,8 @@
     run_unit_test(TestOldFreeSpaceCalculation_test());
     run_unit_test(TestG1BiasedArray_test());
     run_unit_test(HeapRegionRemSet::test_prt());
+    run_unit_test(SpaceManager_test_adjust_initial_chunk_size());
+    run_unit_test(ChunkManager_test_list_index());
     run_unit_test(TestBufferingOopClosure_test());
     run_unit_test(TestCodeCacheRemSet_test());
     if (UseG1GC) {
diff --git a/hotspot/src/share/vm/runtime/thread.cpp b/hotspot/src/share/vm/runtime/thread.cpp
index 0dc86d9..71b3b2d 100644
--- a/hotspot/src/share/vm/runtime/thread.cpp
+++ b/hotspot/src/share/vm/runtime/thread.cpp
@@ -3242,6 +3242,9 @@
   _scanned_nmethod = NULL;
   _compiler = NULL;
 
+  // Compiler uses resource area for compilation, let's bias it to mtCompiler
+  resource_area()->bias_to(mtCompiler);
+
 #ifndef PRODUCT
   _ideal_graph_printer = NULL;
 #endif
diff --git a/hotspot/src/share/vm/runtime/vm_operations.hpp b/hotspot/src/share/vm/runtime/vm_operations.hpp
index fb99be9..cc32b97 100644
--- a/hotspot/src/share/vm/runtime/vm_operations.hpp
+++ b/hotspot/src/share/vm/runtime/vm_operations.hpp
@@ -97,6 +97,7 @@
   template(LinuxDllLoad)                          \
   template(RotateGCLog)                           \
   template(WhiteBoxOperation)                     \
+  template(ClassLoaderStatsOperation)             \
 
 class VM_Operation: public CHeapObj<mtInternal> {
  public:
diff --git a/hotspot/src/share/vm/services/diagnosticCommand.cpp b/hotspot/src/share/vm/services/diagnosticCommand.cpp
index f9551c9..ede8db1 100644
--- a/hotspot/src/share/vm/services/diagnosticCommand.cpp
+++ b/hotspot/src/share/vm/services/diagnosticCommand.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
+ * 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
@@ -23,14 +23,17 @@
  */
 
 #include "precompiled.hpp"
+#include "classfile/classLoaderStats.hpp"
 #include "gc_implementation/shared/vmGCOperations.hpp"
 #include "runtime/javaCalls.hpp"
+#include "runtime/os.hpp"
 #include "services/diagnosticArgument.hpp"
 #include "services/diagnosticCommand.hpp"
 #include "services/diagnosticFramework.hpp"
 #include "services/heapDumper.hpp"
 #include "services/management.hpp"
 #include "utilities/macros.hpp"
+#include "oops/objArrayOop.hpp"
 
 PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
 
@@ -46,9 +49,12 @@
   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<CommandLineDCmd>(full_export, true, false));
   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<PrintSystemPropertiesDCmd>(full_export, true, false));
   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<PrintVMFlagsDCmd>(full_export, true, false));
+  DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<VMDynamicLibrariesDCmd>(full_export, true, false));
   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<VMUptimeDCmd>(full_export, true, false));
   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<SystemGCDCmd>(full_export, true, false));
   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<RunFinalizationDCmd>(full_export, true, false));
+  DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<HeapInfoDCmd>(full_export, true, false));
+  DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<FinalizerInfoDCmd>(full_export, true, false));
 #if INCLUDE_SERVICES // Heap dumping/inspection supported
   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<HeapDumpDCmd>(DCmd_Source_Internal | DCmd_Source_AttachAPI, true, false));
   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<ClassHistogramDCmd>(full_export, true, false));
@@ -56,6 +62,7 @@
 #endif // INCLUDE_SERVICES
   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<ThreadDumpDCmd>(full_export, true, false));
   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<RotateGCLogDCmd>(full_export, true, false));
+  DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<ClassLoaderStatsDCmd>(full_export, true, false));
 
   // Enhanced JMX Agent Support
   // These commands won't be exported via the DiagnosticCommandMBean until an
@@ -273,6 +280,60 @@
                          vmSymbols::void_method_signature(), CHECK);
 }
 
+void HeapInfoDCmd::execute(DCmdSource source, TRAPS) {
+  Universe::heap()->print_on(output());
+}
+
+void FinalizerInfoDCmd::execute(DCmdSource source, TRAPS) {
+  ResourceMark rm;
+
+
+  Klass* k = SystemDictionary::resolve_or_null(
+    vmSymbols::finalizer_histogram_klass(), THREAD);
+  assert(k != NULL, "FinalizerHistogram class is not accessible");
+
+  instanceKlassHandle klass(THREAD, k);
+  JavaValue result(T_ARRAY);
+
+  // We are calling lang.ref.FinalizerHistogram.getFinalizerHistogram() method
+  // and expect it to return array of FinalizerHistogramEntry as Object[]
+
+  JavaCalls::call_static(&result, klass,
+                         vmSymbols::get_finalizer_histogram_name(),
+                         vmSymbols::void_finalizer_histogram_entry_array_signature(), CHECK);
+
+  objArrayOop result_oop = (objArrayOop) result.get_jobject();
+  if (result_oop->length() == 0) {
+    output()->print_cr("No instances waiting for finalization found");
+    return;
+  }
+
+  oop foop = result_oop->obj_at(0);
+  InstanceKlass* ik = InstanceKlass::cast(foop->klass());
+
+  fieldDescriptor count_fd, name_fd;
+
+  Klass* count_res = ik->find_field(
+    vmSymbols::finalizer_histogram_entry_count_field(), vmSymbols::int_signature(), &count_fd);
+
+  Klass* name_res = ik->find_field(
+    vmSymbols::finalizer_histogram_entry_name_field(), vmSymbols::string_signature(), &name_fd);
+
+  assert(count_res != NULL && name_res != NULL, "Unexpected layout of FinalizerHistogramEntry");
+
+  output()->print_cr("Unreachable instances waiting for finalization");
+  output()->print_cr("#instances  class name");
+  output()->print_cr("-----------------------");
+
+  for (int i = 0; i < result_oop->length(); ++i) {
+    oop element_oop = result_oop->obj_at(i);
+    oop str_oop = element_oop->obj_field(name_fd.offset());
+    char *name = java_lang_String::as_utf8_string(str_oop);
+    int count = element_oop->int_field(count_fd.offset());
+    output()->print_cr("%10d  %s", count, name);
+  }
+}
+
 #if INCLUDE_SERVICES // Heap dumping/inspection supported
 HeapDumpDCmd::HeapDumpDCmd(outputStream* output, bool heap) :
                            DCmdWithParser(output, heap),
@@ -619,8 +680,7 @@
 }
 
 JMXStartLocalDCmd::JMXStartLocalDCmd(outputStream *output, bool heap_allocated) :
-  DCmd(output, heap_allocated)
-{
+  DCmd(output, heap_allocated) {
   // do nothing
 }
 
@@ -641,7 +701,6 @@
     JavaCalls::call_static(&result, ik, vmSymbols::startLocalAgent_name(), vmSymbols::void_method_signature(), CHECK);
 }
 
-
 void JMXStopRemoteDCmd::execute(DCmdSource source, TRAPS) {
     ResourceMark rm(THREAD);
     HandleMark hm(THREAD);
@@ -659,6 +718,16 @@
     JavaCalls::call_static(&result, ik, vmSymbols::stopRemoteAgent_name(), vmSymbols::void_method_signature(), CHECK);
 }
 
+VMDynamicLibrariesDCmd::VMDynamicLibrariesDCmd(outputStream *output, bool heap_allocated) :
+  DCmd(output, heap_allocated) {
+  // do nothing
+}
+
+void VMDynamicLibrariesDCmd::execute(DCmdSource source, TRAPS) {
+  os::print_dll_info(output());
+  output()->cr();
+}
+
 void RotateGCLogDCmd::execute(DCmdSource source, TRAPS) {
   if (UseGCLogFileRotation) {
     VM_RotateGCLog rotateop(output());
diff --git a/hotspot/src/share/vm/services/diagnosticCommand.hpp b/hotspot/src/share/vm/services/diagnosticCommand.hpp
index 3fda342..b1fb57e 100644
--- a/hotspot/src/share/vm/services/diagnosticCommand.hpp
+++ b/hotspot/src/share/vm/services/diagnosticCommand.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
+ * 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
@@ -132,6 +132,29 @@
   virtual void execute(DCmdSource source, TRAPS);
 };
 
+class VMDynamicLibrariesDCmd : public DCmd {
+public:
+  VMDynamicLibrariesDCmd(outputStream* output, bool heap);
+  static const char* name() {
+    return "VM.dynlibs";
+  }
+  static const char* description() {
+    return "Print loaded dynamic libraries.";
+  }
+  static const char* impact() {
+    return "Low";
+  }
+  static const JavaPermission permission() {
+    JavaPermission p = {"java.lang.management.ManagementPermission",
+                        "monitor", NULL};
+    return p;
+  }
+  static int num_arguments() {
+    return 0;
+  };
+  virtual void execute(DCmdSource source, TRAPS);
+};
+
 class VMUptimeDCmd : public DCmdWithParser {
 protected:
   DCmdArgument<bool> _date;
@@ -176,6 +199,46 @@
     virtual void execute(DCmdSource source, TRAPS);
 };
 
+class HeapInfoDCmd : public DCmd {
+public:
+  HeapInfoDCmd(outputStream* output, bool heap) : DCmd(output, heap) { }
+  static const char* name() { return "GC.heap_info"; }
+  static const char* description() {
+    return "Provide generic Java heap information.";
+  }
+  static const char* impact() {
+    return "Medium";
+  }
+  static int num_arguments() { return 0; }
+  static const JavaPermission permission() {
+    JavaPermission p = {"java.lang.management.ManagementPermission",
+      "monitor", NULL};
+      return p;
+  }
+
+  virtual void execute(DCmdSource source, TRAPS);
+};
+
+class FinalizerInfoDCmd : public DCmd {
+public:
+  FinalizerInfoDCmd(outputStream* output, bool heap) : DCmd(output, heap) { }
+  static const char* name() { return "GC.finalizer_info"; }
+  static const char* description() {
+    return "Provide information about Java finalization queue.";
+  }
+  static const char* impact() {
+    return "Medium";
+  }
+  static int num_arguments() { return 0; }
+  static const JavaPermission permission() {
+    JavaPermission p = {"java.lang.management.ManagementPermission",
+      "monitor", NULL};
+      return p;
+  }
+
+  virtual void execute(DCmdSource source, TRAPS);
+};
+
 #if INCLUDE_SERVICES   // Heap dumping supported
 // See also: dump_heap in attachListener.cpp
 class HeapDumpDCmd : public DCmdWithParser {
diff --git a/hotspot/src/share/vm/services/mallocSiteTable.cpp b/hotspot/src/share/vm/services/mallocSiteTable.cpp
index 8090de8..861c5a3 100644
--- a/hotspot/src/share/vm/services/mallocSiteTable.cpp
+++ b/hotspot/src/share/vm/services/mallocSiteTable.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -97,7 +97,7 @@
 
   // Instantiate hash entry for hashtable entry allocation callsite
   MallocSiteHashtableEntry* entry = ::new ((void*)_hash_entry_allocation_site)
-    MallocSiteHashtableEntry(*stack);
+    MallocSiteHashtableEntry(*stack, mtNMT);
 
   // Add the allocation site to hashtable.
   int index = hash_to_index(stack->hash());
@@ -134,7 +134,8 @@
  *  Under any of above circumstances, caller should handle the situation.
  */
 MallocSite* MallocSiteTable::lookup_or_add(const NativeCallStack& key, size_t* bucket_idx,
-  size_t* pos_idx) {
+  size_t* pos_idx, MEMFLAGS flags) {
+  assert(flags != mtNone, "Should have a real memory type");
   int index = hash_to_index(key.hash());
   assert(index >= 0, "Negative index");
   *bucket_idx = (size_t)index;
@@ -142,7 +143,7 @@
 
   // First entry for this hash bucket
   if (_table[index] == NULL) {
-    MallocSiteHashtableEntry* entry = new_entry(key);
+    MallocSiteHashtableEntry* entry = new_entry(key, flags);
     // OOM check
     if (entry == NULL) return NULL;
 
@@ -157,13 +158,12 @@
   MallocSiteHashtableEntry* head = _table[index];
   while (head != NULL && (*pos_idx) <= MAX_BUCKET_LENGTH) {
     MallocSite* site = head->data();
-    if (site->equals(key)) {
-      // found matched entry
+    if (site->flags() == flags && site->equals(key)) {
       return head->data();
     }
 
     if (head->next() == NULL && (*pos_idx) < MAX_BUCKET_LENGTH) {
-      MallocSiteHashtableEntry* entry = new_entry(key);
+      MallocSiteHashtableEntry* entry = new_entry(key, flags);
       // OOM check
       if (entry == NULL) return NULL;
       if (head->atomic_insert(entry)) {
@@ -192,10 +192,10 @@
 // Allocates MallocSiteHashtableEntry object. Special call stack
 // (pre-installed allocation site) has to be used to avoid infinite
 // recursion.
-MallocSiteHashtableEntry* MallocSiteTable::new_entry(const NativeCallStack& key) {
+MallocSiteHashtableEntry* MallocSiteTable::new_entry(const NativeCallStack& key, MEMFLAGS flags) {
   void* p = AllocateHeap(sizeof(MallocSiteHashtableEntry), mtNMT,
     *hash_entry_allocation_stack(), AllocFailStrategy::RETURN_NULL);
-  return ::new (p) MallocSiteHashtableEntry(key);
+  return ::new (p) MallocSiteHashtableEntry(key, flags);
 }
 
 void MallocSiteTable::reset() {
diff --git a/hotspot/src/share/vm/services/mallocSiteTable.hpp b/hotspot/src/share/vm/services/mallocSiteTable.hpp
index cff9816..36c4e5c 100644
--- a/hotspot/src/share/vm/services/mallocSiteTable.hpp
+++ b/hotspot/src/share/vm/services/mallocSiteTable.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -37,12 +37,16 @@
 // MallocSite represents a code path that eventually calls
 // os::malloc() to allocate memory
 class MallocSite : public AllocationSite<MemoryCounter> {
+ private:
+  MEMFLAGS _flags;
+
  public:
   MallocSite() :
-    AllocationSite<MemoryCounter>(NativeCallStack::EMPTY_STACK) { }
+    AllocationSite<MemoryCounter>(NativeCallStack::EMPTY_STACK), _flags(mtNone) {}
 
-  MallocSite(const NativeCallStack& stack) :
-    AllocationSite<MemoryCounter>(stack) { }
+  MallocSite(const NativeCallStack& stack, MEMFLAGS flags) :
+    AllocationSite<MemoryCounter>(stack), _flags(flags) {}
+
 
   void allocate(size_t size)      { data()->allocate(size);   }
   void deallocate(size_t size)    { data()->deallocate(size); }
@@ -51,6 +55,7 @@
   size_t size()  const { return peek()->size(); }
   // The number of calls were made
   size_t count() const { return peek()->count(); }
+  MEMFLAGS flags() const { return (MEMFLAGS)_flags; }
 };
 
 // Malloc site hashtable entry
@@ -62,8 +67,10 @@
  public:
   MallocSiteHashtableEntry() : _next(NULL) { }
 
-  MallocSiteHashtableEntry(NativeCallStack stack):
-    _malloc_site(stack), _next(NULL) { }
+  MallocSiteHashtableEntry(NativeCallStack stack, MEMFLAGS flags):
+    _malloc_site(stack, flags), _next(NULL) {
+    assert(flags != mtNone, "Expect a real memory type");
+  }
 
   inline const MallocSiteHashtableEntry* next() const {
     return _next;
@@ -198,11 +205,11 @@
   //  1. out of memory
   //  2. overflow hash bucket
   static inline bool allocation_at(const NativeCallStack& stack, size_t size,
-    size_t* bucket_idx, size_t* pos_idx) {
+    size_t* bucket_idx, size_t* pos_idx, MEMFLAGS flags) {
     AccessLock locker(&_access_count);
     if (locker.sharedLock()) {
       NOT_PRODUCT(_peak_count = MAX2(_peak_count, _access_count);)
-      MallocSite* site = lookup_or_add(stack, bucket_idx, pos_idx);
+      MallocSite* site = lookup_or_add(stack, bucket_idx, pos_idx, flags);
       if (site != NULL) site->allocate(size);
       return site != NULL;
     }
@@ -228,13 +235,13 @@
   static bool walk_malloc_site(MallocSiteWalker* walker);
 
  private:
-  static MallocSiteHashtableEntry* new_entry(const NativeCallStack& key);
+  static MallocSiteHashtableEntry* new_entry(const NativeCallStack& key, MEMFLAGS flags);
   static void reset();
 
   // Delete a bucket linked list
   static void delete_linked_list(MallocSiteHashtableEntry* head);
 
-  static MallocSite* lookup_or_add(const NativeCallStack& key, size_t* bucket_idx, size_t* pos_idx);
+  static MallocSite* lookup_or_add(const NativeCallStack& key, size_t* bucket_idx, size_t* pos_idx, MEMFLAGS flags);
   static MallocSite* malloc_site(size_t bucket_idx, size_t pos_idx);
   static bool walk(MallocSiteWalker* walker);
 
diff --git a/hotspot/src/share/vm/services/mallocTracker.cpp b/hotspot/src/share/vm/services/mallocTracker.cpp
index dc4f08f..8d32df3 100644
--- a/hotspot/src/share/vm/services/mallocTracker.cpp
+++ b/hotspot/src/share/vm/services/mallocTracker.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -78,8 +78,8 @@
 }
 
 bool MallocHeader::record_malloc_site(const NativeCallStack& stack, size_t size,
-  size_t* bucket_idx, size_t* pos_idx) const {
-  bool ret =  MallocSiteTable::allocation_at(stack, size, bucket_idx, pos_idx);
+  size_t* bucket_idx, size_t* pos_idx, MEMFLAGS flags) const {
+  bool ret = MallocSiteTable::allocation_at(stack, size, bucket_idx, pos_idx, flags);
 
   // Something went wrong, could be OOM or overflow malloc site table.
   // We want to keep tracking data under OOM circumstance, so transition to
diff --git a/hotspot/src/share/vm/services/mallocTracker.hpp b/hotspot/src/share/vm/services/mallocTracker.hpp
index 3c61aa4..d770e41 100644
--- a/hotspot/src/share/vm/services/mallocTracker.hpp
+++ b/hotspot/src/share/vm/services/mallocTracker.hpp
@@ -268,7 +268,7 @@
     if (level == NMT_detail) {
       size_t bucket_idx;
       size_t pos_idx;
-      if (record_malloc_site(stack, size, &bucket_idx, &pos_idx)) {
+      if (record_malloc_site(stack, size, &bucket_idx, &pos_idx, flags)) {
         assert(bucket_idx <= MAX_MALLOCSITE_TABLE_SIZE, "Overflow bucket index");
         assert(pos_idx <= MAX_BUCKET_LENGTH, "Overflow bucket position index");
         _bucket_idx = bucket_idx;
@@ -292,7 +292,7 @@
     _size = size;
   }
   bool record_malloc_site(const NativeCallStack& stack, size_t size,
-    size_t* bucket_idx, size_t* pos_idx) const;
+    size_t* bucket_idx, size_t* pos_idx, MEMFLAGS flags) const;
 };
 
 
diff --git a/hotspot/src/share/vm/services/memBaseline.cpp b/hotspot/src/share/vm/services/memBaseline.cpp
index 02b4924..f580aad 100644
--- a/hotspot/src/share/vm/services/memBaseline.cpp
+++ b/hotspot/src/share/vm/services/memBaseline.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -59,6 +59,15 @@
   return s1.call_stack()->compare(*s2.call_stack());
 }
 
+// Sort into allocation site addresses and memory type order for baseline comparison
+int compare_malloc_site_and_type(const MallocSite& s1, const MallocSite& s2) {
+  int res = compare_malloc_site(s1, s2);
+  if (res == 0) {
+    res = (int)(s1.flags() - s2.flags());
+  }
+
+  return res;
+}
 
 int compare_virtual_memory_site(const VirtualMemoryAllocationSite& s1,
   const VirtualMemoryAllocationSite& s2) {
@@ -225,6 +234,9 @@
     case by_site:
       malloc_sites_to_allocation_site_order();
       break;
+    case by_site_and_type:
+      malloc_sites_to_allocation_site_and_type_order();
+      break;
     case by_address:
     default:
       ShouldNotReachHere();
@@ -263,7 +275,7 @@
 }
 
 void MemBaseline::malloc_sites_to_allocation_site_order() {
-  if (_malloc_sites_order != by_site) {
+  if (_malloc_sites_order != by_site && _malloc_sites_order != by_site_and_type) {
     SortedLinkedList<MallocSite, compare_malloc_site> tmp;
     // Add malloc sites to sorted linked list to sort into site (address) order
     tmp.move(&_malloc_sites);
@@ -273,6 +285,17 @@
   }
 }
 
+void MemBaseline::malloc_sites_to_allocation_site_and_type_order() {
+  if (_malloc_sites_order != by_site_and_type) {
+    SortedLinkedList<MallocSite, compare_malloc_site_and_type> tmp;
+    // Add malloc sites to sorted linked list to sort into site (address) order
+    tmp.move(&_malloc_sites);
+    _malloc_sites.set_head(tmp.head());
+    tmp.set_head(NULL);
+    _malloc_sites_order = by_site_and_type;
+  }
+}
+
 void MemBaseline::virtual_memory_sites_to_size_order() {
   if (_virtual_memory_sites_order != by_size) {
     SortedLinkedList<VirtualMemoryAllocationSite, compare_virtual_memory_size> tmp;
diff --git a/hotspot/src/share/vm/services/memBaseline.hpp b/hotspot/src/share/vm/services/memBaseline.hpp
index fdcb76d..238d29d 100644
--- a/hotspot/src/share/vm/services/memBaseline.hpp
+++ b/hotspot/src/share/vm/services/memBaseline.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -55,9 +55,10 @@
   };
 
   enum SortingOrder {
-    by_address,   // by memory address
-    by_size,      // by memory size
-    by_site       // by call site where the memory is allocated from
+    by_address,      // by memory address
+    by_size,         // by memory size
+    by_site,         // by call site where the memory is allocated from
+    by_site_and_type // by call site and memory type
   };
 
  private:
@@ -188,6 +189,8 @@
   void malloc_sites_to_size_order();
   // Sort allocation sites in call site address order
   void malloc_sites_to_allocation_site_order();
+  // Sort allocation sites in call site address and memory type order
+  void malloc_sites_to_allocation_site_and_type_order();
 
   // Sort allocation sites in reserved size order
   void virtual_memory_sites_to_size_order();
diff --git a/hotspot/src/share/vm/services/memReporter.cpp b/hotspot/src/share/vm/services/memReporter.cpp
index 0269619..8199ee0 100644
--- a/hotspot/src/share/vm/services/memReporter.cpp
+++ b/hotspot/src/share/vm/services/memReporter.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -43,11 +43,16 @@
     amount_in_current_scale(reserved), scale, amount_in_current_scale(committed), scale);
 }
 
-void MemReporterBase::print_malloc(size_t amount, size_t count) const {
+void MemReporterBase::print_malloc(size_t amount, size_t count, MEMFLAGS flag) const {
   const char* scale = current_scale();
   outputStream* out = output();
-  out->print("(malloc=" SIZE_FORMAT "%s",
-    amount_in_current_scale(amount), scale);
+  if (flag != mtNone) {
+    out->print("(malloc=" SIZE_FORMAT "%s type=%s",
+      amount_in_current_scale(amount), scale, NMTUtil::flag_to_name(flag));
+  } else {
+    out->print("(malloc=" SIZE_FORMAT "%s",
+      amount_in_current_scale(amount), scale);
+  }
 
   if (count > 0) {
     out->print(" #" SIZE_FORMAT "", count);
@@ -200,7 +205,10 @@
     const NativeCallStack* stack = malloc_site->call_stack();
     stack->print_on(out);
     out->print("%29s", " ");
-    print_malloc(malloc_site->size(), malloc_site->count());
+    MEMFLAGS flag = malloc_site->flags();
+    assert((flag >= 0 && flag < (int)mt_number_of_types) && flag != mtNone,
+      "Must have a valid memory type");
+    print_malloc(malloc_site->size(), malloc_site->count(),flag);
     out->print_cr("\n");
   }
 }
@@ -304,11 +312,16 @@
 }
 
 void MemSummaryDiffReporter::print_malloc_diff(size_t current_amount, size_t current_count,
-    size_t early_amount, size_t early_count) const {
+    size_t early_amount, size_t early_count, MEMFLAGS flags) const {
   const char* scale = current_scale();
   outputStream* out = output();
 
   out->print("malloc=" SIZE_FORMAT "%s", amount_in_current_scale(current_amount), scale);
+  // Report type only if it is valid
+  if (flags != mtNone) {
+    out->print(" type=%s", NMTUtil::flag_to_name(flags));
+  }
+
   long amount_diff = diff_in_current_scale(current_amount, early_amount);
   if (amount_diff != 0) {
     out->print(" %+ld%s", amount_diff, scale);
@@ -437,7 +450,7 @@
         diff_in_current_scale(current_malloc_amount, early_malloc_amount) != 0) {
       out->print("%28s(", " ");
       print_malloc_diff(current_malloc_amount, (flag == mtChunk) ? 0 : current_malloc->malloc_count(),
-        early_malloc_amount, early_malloc->malloc_count());
+        early_malloc_amount, early_malloc->malloc_count(), mtNone);
       out->print_cr(")");
     }
 
@@ -485,8 +498,8 @@
 }
 
 void MemDetailDiffReporter::diff_malloc_sites() const {
-  MallocSiteIterator early_itr = _early_baseline.malloc_sites(MemBaseline::by_site);
-  MallocSiteIterator current_itr = _current_baseline.malloc_sites(MemBaseline::by_site);
+  MallocSiteIterator early_itr = _early_baseline.malloc_sites(MemBaseline::by_site_and_type);
+  MallocSiteIterator current_itr = _current_baseline.malloc_sites(MemBaseline::by_site_and_type);
 
   const MallocSite* early_site   = early_itr.next();
   const MallocSite* current_site = current_itr.next();
@@ -549,22 +562,23 @@
 
 void MemDetailDiffReporter::new_malloc_site(const MallocSite* malloc_site) const {
   diff_malloc_site(malloc_site->call_stack(), malloc_site->size(), malloc_site->count(),
-    0, 0);
+    0, 0, malloc_site->flags());
 }
 
 void MemDetailDiffReporter::old_malloc_site(const MallocSite* malloc_site) const {
   diff_malloc_site(malloc_site->call_stack(), 0, 0, malloc_site->size(),
-    malloc_site->count());
+    malloc_site->count(), malloc_site->flags());
 }
 
 void MemDetailDiffReporter::diff_malloc_site(const MallocSite* early,
   const MallocSite* current)  const {
+  assert(early->flags() == current->flags(), "Must be the same memory type");
   diff_malloc_site(current->call_stack(), current->size(), current->count(),
-    early->size(), early->count());
+    early->size(), early->count(), early->flags());
 }
 
 void MemDetailDiffReporter::diff_malloc_site(const NativeCallStack* stack, size_t current_size,
-  size_t current_count, size_t early_size, size_t early_count) const {
+  size_t current_count, size_t early_size, size_t early_count, MEMFLAGS flags) const {
   outputStream* out = output();
 
   assert(stack != NULL, "NULL stack");
@@ -576,7 +590,7 @@
   stack->print_on(out);
   out->print("%28s (", " ");
   print_malloc_diff(current_size, current_count,
-    early_size, early_count);
+    early_size, early_count, flags);
 
   out->print_cr(")\n");
 }
diff --git a/hotspot/src/share/vm/services/memReporter.hpp b/hotspot/src/share/vm/services/memReporter.hpp
index 951076c..9b83f8c 100644
--- a/hotspot/src/share/vm/services/memReporter.hpp
+++ b/hotspot/src/share/vm/services/memReporter.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -76,7 +76,7 @@
 
   // Print summary total, malloc and virtual memory
   void print_total(size_t reserved, size_t committed) const;
-  void print_malloc(size_t amount, size_t count) const;
+  void print_malloc(size_t amount, size_t count, MEMFLAGS flag = mtNone) const;
   void print_virtual_memory(size_t reserved, size_t committed) const;
 
   void print_malloc_line(size_t amount, size_t count) const;
@@ -174,7 +174,7 @@
 
  protected:
   void print_malloc_diff(size_t current_amount, size_t current_count,
-    size_t early_amount, size_t early_count) const;
+    size_t early_amount, size_t early_count, MEMFLAGS flags) const;
   void print_virtual_memory_diff(size_t current_reserved, size_t current_committed,
     size_t early_reserved, size_t early_committed) const;
   void print_arena_diff(size_t current_amount, size_t current_count,
@@ -216,7 +216,7 @@
                                 const VirtualMemoryAllocationSite* current)  const;
 
   void diff_malloc_site(const NativeCallStack* stack, size_t current_size,
-    size_t currrent_count, size_t early_size, size_t early_count) const;
+    size_t currrent_count, size_t early_size, size_t early_count, MEMFLAGS flags) const;
   void diff_virtual_memory_site(const NativeCallStack* stack, size_t current_reserved,
     size_t current_committed, size_t early_reserved, size_t early_committed) const;
 };
diff --git a/hotspot/src/share/vm/utilities/debug.cpp b/hotspot/src/share/vm/utilities/debug.cpp
index 232f350..4f7cbdd 100644
--- a/hotspot/src/share/vm/utilities/debug.cpp
+++ b/hotspot/src/share/vm/utilities/debug.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -315,6 +315,14 @@
   }
 }
 
+void report_insufficient_metaspace(size_t required_size) {
+  warning("\nThe MaxMetaspaceSize of " SIZE_FORMAT " bytes is not large enough.\n"
+          "Either don't specify the -XX:MaxMetaspaceSize=<size>\n"
+          "or increase the size to at least " SIZE_FORMAT ".\n",
+          MaxMetaspaceSize, required_size);
+  exit(2);
+}
+
 static bool error_reported = false;
 
 // call this when the VM is dying--it might loosen some asserts
diff --git a/hotspot/src/share/vm/utilities/debug.hpp b/hotspot/src/share/vm/utilities/debug.hpp
index 5b47e61..86fc6b1 100644
--- a/hotspot/src/share/vm/utilities/debug.hpp
+++ b/hotspot/src/share/vm/utilities/debug.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -222,6 +222,7 @@
 void report_should_not_reach_here(const char* file, int line);
 void report_unimplemented(const char* file, int line);
 void report_untested(const char* file, int line, const char* message);
+void report_insufficient_metaspace(size_t required_size);
 
 void warning(const char* format, ...) ATTRIBUTE_PRINTF(1, 2);
 
diff --git a/hotspot/test/TEST.groups b/hotspot/test/TEST.groups
index f2209c8..4075036 100644
--- a/hotspot/test/TEST.groups
+++ b/hotspot/test/TEST.groups
@@ -96,6 +96,7 @@
   runtime/XCheckJniJsig/XCheckJSig.java \
   serviceability/attach/AttachWithStalePidFile.java \
   serviceability/sa/jmap-hprof/JMapHProfLargeHeapTest.java \
+  serviceability/dcmd/DynLibDcmdTest.java \
   testlibrary_tests/
 
 
diff --git a/hotspot/test/compiler/loopopts/TestCMovSplitThruPhi.java b/hotspot/test/compiler/loopopts/TestCMovSplitThruPhi.java
new file mode 100644
index 0000000..03df3c0
--- /dev/null
+++ b/hotspot/test/compiler/loopopts/TestCMovSplitThruPhi.java
@@ -0,0 +1,67 @@
+/*
+ * Copyright (c) 2017, Red Hat, Inc. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/**
+ * @test
+ * @bug 8187822
+ * @summary C2 conditonal move optimization might create broken graph
+ * @run main/othervm -XX:-UseOnStackReplacement -XX:-BackgroundCompilation -XX:CompileCommand=dontinline,TestCMovSplitThruPhi::not_inlined -XX:CompileOnly=TestCMovSplitThruPhi::test -XX:-LoopUnswitching TestCMovSplitThruPhi
+ *
+ */
+
+public class TestCMovSplitThruPhi {
+    static int f;
+
+    static int test(boolean flag1, boolean flag2, boolean flag3, boolean flag4) {
+        int v3 = 0;
+        if (flag4) {
+            for (int i = 0; i < 10; i++) {
+                int v1 = 0;
+                if (flag1) {
+                    v1 = not_inlined();
+                }
+                // AddI below will be candidate for split through Phi
+                int v2 = v1;
+                if (flag2) {
+                    v2 = f + v1;
+                }
+                // test above will be converted to CMovI
+                if (flag3) {
+                    v3 = v2 * 2;
+                    break;
+                }
+            }
+        }
+        return v3;
+    }
+
+    private static int not_inlined() {
+        return 0;
+    }
+
+    public static void main(String[] args) {
+        for (int i = 0; i < 20000; i++) {
+            test((i % 2) == 0, (i % 2) == 0, (i % 100) == 1, (i % 1000) == 1);
+        }
+    }
+}
diff --git a/hotspot/test/serviceability/dcmd/ClassLoaderStatsTest.java b/hotspot/test/serviceability/dcmd/ClassLoaderStatsTest.java
new file mode 100644
index 0000000..c22b080
--- /dev/null
+++ b/hotspot/test/serviceability/dcmd/ClassLoaderStatsTest.java
@@ -0,0 +1,155 @@
+/*
+ * Copyright (c) 2014, 2017, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ *
+ * @build ClassLoaderStatsTest DcmdUtil
+ * @run main ClassLoaderStatsTest
+ */
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.StringReader;
+import java.nio.ByteBuffer;
+import java.nio.channels.FileChannel;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+public class ClassLoaderStatsTest {
+
+    // ClassLoader         Parent              CLD*               Classes   ChunkSz   BlockSz  Type
+    // 0x00000007c0215928  0x0000000000000000  0x0000000000000000       0         0         0  org.eclipse.osgi.baseadaptor.BaseAdaptor$1
+    // 0x00000007c0009868  0x0000000000000000  0x00007fc52aebcc80       1      6144      3768  sun.reflect.DelegatingClassLoader
+    // 0x00000007c0009868  0x0000000000000000  0x00007fc52b8916d0       1      6144      3688  sun.reflect.DelegatingClassLoader
+    // 0x00000007c0009868  0x00000007c0038ba8  0x00007fc52afb8760       1      6144      3688  sun.reflect.DelegatingClassLoader
+    // 0x00000007c0009868  0x0000000000000000  0x00007fc52afbb1a0       1      6144      3688  sun.reflect.DelegatingClassLoader
+    // 0x0000000000000000  0x0000000000000000  0x00007fc523416070    5019  30060544  29956216  <boot classloader>
+    //                                                                455   1210368    672848   + unsafe anonymous classes
+    // 0x00000007c016b5c8  0x00000007c0038ba8  0x00007fc52a995000       5      8192      5864  org.netbeans.StandardModule$OneModuleClassLoader
+    // 0x00000007c0009868  0x00000007c016b5c8  0x00007fc52ac13640       1      6144      3896  sun.reflect.DelegatingClassLoader
+    // ...
+
+    static Pattern clLine = Pattern.compile("0x\\p{XDigit}*\\s*0x\\p{XDigit}*\\s*0x\\p{XDigit}*\\s*(\\d*)\\s*(\\d*)\\s*(\\d*)\\s*(.*)");
+    static Pattern anonLine = Pattern.compile("\\s*(\\d*)\\s*(\\d*)\\s*(\\d*)\\s*.*");
+
+    public static DummyClassLoader dummyloader;
+
+    public static void main(String arg[]) throws Exception {
+
+        // create a classloader and load our special class
+        dummyloader = new DummyClassLoader();
+        Class<?> c = Class.forName("TestClass", true, dummyloader);
+        if (c.getClassLoader() != dummyloader) {
+            throw new RuntimeException("TestClass defined by wrong classloader: " + c.getClassLoader());
+        }
+
+        String result = DcmdUtil.executeDcmd("VM.classloader_stats");
+        BufferedReader r = new BufferedReader(new StringReader(result));
+        String line;
+        while((line = r.readLine()) != null) {
+            Matcher m = clLine.matcher(line);
+            if (m.matches()) {
+                // verify that DummyClassLoader has loaded 1 class and 1 anonymous class
+                if (m.group(4).equals("ClassLoaderStatsTest$DummyClassLoader")) {
+                    System.out.println("line: " + line);
+                    if (!m.group(1).equals("1")) {
+                        throw new Exception("Should have loaded 1 class: " + line);
+                    }
+                    checkPositiveInt(m.group(2));
+                    checkPositiveInt(m.group(3));
+
+                    String next = r.readLine();
+                    System.out.println("next: " + next);
+                    Matcher m1 = anonLine.matcher(next);
+                    m1.matches();
+                    if (!m1.group(1).equals("1")) {
+                        throw new Exception("Should have loaded 1 anonymous class, but found : " + m1.group(1));
+                    }
+                    checkPositiveInt(m1.group(2));
+                    checkPositiveInt(m1.group(3));
+                }
+            }
+        }
+    }
+
+    private static void checkPositiveInt(String s) throws Exception {
+        if (Integer.parseInt(s) <= 0) {
+            throw new Exception("Value should have been > 0: " + s);
+        }
+    }
+
+    public static class DummyClassLoader extends ClassLoader {
+
+        public static final String CLASS_NAME = "TestClass";
+
+        static ByteBuffer readClassFile(String name)
+        {
+            File f = new File(System.getProperty("test.classes", "."),
+                              name);
+            try (FileInputStream fin = new FileInputStream(f);
+                 FileChannel fc = fin.getChannel())
+            {
+                return fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
+            } catch (IOException e) {
+                throw new RuntimeException("Can't open file: " + name, e);
+            }
+        }
+
+        protected Class<?> loadClass(String name, boolean resolve)
+            throws ClassNotFoundException
+        {
+            Class<?> c;
+            if (!"TestClass".equals(name)) {
+                c = super.loadClass(name, resolve);
+            } else {
+                // should not delegate to the system class loader
+                c = findClass(name);
+                if (resolve) {
+                    resolveClass(c);
+                }
+            }
+            return c;
+        }
+
+        protected Class<?> findClass(String name)
+            throws ClassNotFoundException
+        {
+            if (!"TestClass".equals(name)) {
+                throw new ClassNotFoundException("Unexpected class: " + name);
+            }
+            return defineClass(name, readClassFile(name + ".class"), null);
+        }
+    } /* DummyClassLoader */
+
+}
+
+class TestClass {
+    static {
+        // force creation of anonymous class (for the lambdaform)
+        Runnable r = () -> System.out.println("Hello");
+        r.run();
+    }
+}
diff --git a/hotspot/test/serviceability/dcmd/DcmdUtil.java b/hotspot/test/serviceability/dcmd/DcmdUtil.java
new file mode 100644
index 0000000..2542e67
--- /dev/null
+++ b/hotspot/test/serviceability/dcmd/DcmdUtil.java
@@ -0,0 +1,73 @@
+/*
+ * Copyright (c) 2013, 2017, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import sun.management.ManagementFactoryHelper;
+
+import com.sun.management.DiagnosticCommandMBean;
+
+public class DcmdUtil
+{
+    public static String executeDcmd(String cmd, String ... args) {
+        DiagnosticCommandMBean dcmd = ManagementFactoryHelper.getDiagnosticCommandMBean();
+        Object[] dcmdArgs = {args};
+        String[] signature = {String[].class.getName()};
+
+        try {
+            System.out.print("> " + cmd + " ");
+            for (String s : args) {
+                System.out.print(s + " ");
+            }
+            System.out.println(":");
+            String result = (String) dcmd.invoke(transform(cmd), dcmdArgs, signature);
+            System.out.println(result);
+            return result;
+        } catch(Exception ex) {
+            ex.printStackTrace();
+        }
+        return null;
+    }
+
+    private static String transform(String name) {
+        StringBuilder sb = new StringBuilder();
+        boolean toLower = true;
+        boolean toUpper = false;
+        for (int i = 0; i < name.length(); i++) {
+            char c = name.charAt(i);
+            if (c == '.' || c == '_') {
+                toLower = false;
+                toUpper = true;
+            } else {
+                if (toUpper) {
+                    toUpper = false;
+                    sb.append(Character.toUpperCase(c));
+                } else if(toLower) {
+                    sb.append(Character.toLowerCase(c));
+                } else {
+                    sb.append(c);
+                }
+            }
+        }
+        return sb.toString();
+    }
+
+}
diff --git a/hotspot/test/serviceability/dcmd/DynLibDcmdTest.java b/hotspot/test/serviceability/dcmd/DynLibDcmdTest.java
new file mode 100644
index 0000000..c1a4a92
--- /dev/null
+++ b/hotspot/test/serviceability/dcmd/DynLibDcmdTest.java
@@ -0,0 +1,67 @@
+/*
+ * Copyright (c) 2013, 2017, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.util.HashSet;
+import java.util.Set;
+import com.oracle.java.testlibrary.Platform;
+
+/*
+ * @test
+ * @summary Test of VM.dynlib diagnostic command via MBean
+ * @library /testlibrary
+ * @compile DcmdUtil.java
+ * @run main DynLibDcmdTest
+ */
+
+public class DynLibDcmdTest {
+
+    public static void main(String[] args) throws Exception {
+        String result = DcmdUtil.executeDcmd("VM.dynlibs");
+
+        String osDependentBaseString = null;
+        if (Platform.isSolaris()) {
+            osDependentBaseString = "lib%s.so";
+        } else if (Platform.isWindows()) {
+            osDependentBaseString = "%s.dll";
+        } else if (Platform.isOSX()) {
+            osDependentBaseString = "lib%s.dylib";
+        } else if (Platform.isLinux()) {
+            osDependentBaseString = "lib%s.so";
+        }
+
+        if (osDependentBaseString == null) {
+            throw new Exception("Unsupported OS");
+        }
+
+        Set<String> expectedContent = new HashSet<>();
+        expectedContent.add(String.format(osDependentBaseString, "jvm"));
+        expectedContent.add(String.format(osDependentBaseString, "java"));
+        expectedContent.add(String.format(osDependentBaseString, "management"));
+
+        for(String expected : expectedContent) {
+            if (!result.contains(expected)) {
+                throw new Exception("Dynamic library list output did not contain the expected string: '" + expected + "'");
+            }
+        }
+    }
+}
diff --git a/hotspot/test/serviceability/dcmd/gc/FinalizerInfoTest.java b/hotspot/test/serviceability/dcmd/gc/FinalizerInfoTest.java
new file mode 100644
index 0000000..deb7661
--- /dev/null
+++ b/hotspot/test/serviceability/dcmd/gc/FinalizerInfoTest.java
@@ -0,0 +1,87 @@
+/*
+ * Copyright (c) 2015, 2017, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import com.oracle.java.testlibrary.JDKToolFinder;
+import com.oracle.java.testlibrary.OutputAnalyzer;
+import com.oracle.java.testlibrary.ProcessTools;
+
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.Condition;
+import java.util.concurrent.locks.ReentrantLock;
+
+/*
+ * @test
+ * @summary
+ * @library /testlibrary
+ * @run main FinalizerInfoTest
+ */
+public class FinalizerInfoTest {
+    static ReentrantLock lock = new ReentrantLock();
+    static volatile int wasInitialized = 0;
+    static volatile int wasTrapped = 0;
+    static final String cmd = "GC.finalizer_info";
+    static final int objectsCount = 1000;
+
+    class MyObject {
+        public MyObject() {
+            // Make sure object allocation/deallocation is not optimized out
+            wasInitialized += 1;
+        }
+
+        protected void finalize() {
+            // Trap the object in a finalization queue
+            wasTrapped += 1;
+            lock.lock();
+        }
+    }
+
+    void run() throws Exception {
+        try {
+            lock.lock();
+            for(int i = 0; i < objectsCount; ++i) {
+                new MyObject();
+            }
+            System.out.println("Objects initialized: " + objectsCount);
+            System.gc();
+
+            while(wasTrapped < 1) {
+                // Waiting for gc thread.
+            }
+
+
+            String pid = Integer.toString(ProcessTools.getProcessId());
+            ProcessBuilder pb = new ProcessBuilder();
+            pb.command(new String[] { JDKToolFinder.getJDKTool("jcmd"), pid, cmd});
+            OutputAnalyzer output = new OutputAnalyzer(pb.start());
+            output.shouldContain("MyObject");
+        } finally {
+            lock.unlock();
+        }
+    }
+
+    public static void main(String[] args) throws Exception {
+        new  FinalizerInfoTest().run();
+    }
+
+
+}
diff --git a/hotspot/test/serviceability/dcmd/gc/HeapInfoTest.java b/hotspot/test/serviceability/dcmd/gc/HeapInfoTest.java
new file mode 100644
index 0000000..23355cd
--- /dev/null
+++ b/hotspot/test/serviceability/dcmd/gc/HeapInfoTest.java
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) 2015, 2017, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import com.oracle.java.testlibrary.JDKToolFinder;
+import com.oracle.java.testlibrary.OutputAnalyzer;
+import com.oracle.java.testlibrary.ProcessTools;
+
+/*
+ * @test
+ * @summary Test of diagnostic command GC.heap_info
+ * @library /testlibrary
+ * @run main HeapInfoTest
+ */
+public class HeapInfoTest {
+
+    public static void main(String[] args) throws Exception {
+        String pid = Integer.toString(ProcessTools.getProcessId());
+        ProcessBuilder pb = new ProcessBuilder();
+        pb.command(new String[] { JDKToolFinder.getJDKTool("jcmd"), pid, "GC.heap_info"});
+        OutputAnalyzer output = new OutputAnalyzer(pb.start());
+        output.shouldContain("Metaspace");
+    }
+}
+
diff --git a/jaxp/.hgtags b/jaxp/.hgtags
index e64763b..2c905e6 100644
--- a/jaxp/.hgtags
+++ b/jaxp/.hgtags
@@ -855,3 +855,9 @@
 0eb59cc7716f47525b80b9764c86188063e7cfff jdk8u171-b02
 1e523ce5792f08f3dc015084e3f018d6ee0c5859 jdk8u171-b03
 a19f8b3a9242df77ed3df29ceefc30d0b0d2766c jdk8u171-b04
+5279c6da822efa9073793968777a2b3a65376e8e jdk8u171-b05
+dcef061c36284bbf5a9f7093dcbc134b9f62e9f5 jdk8u172-b00
+a8bd8d03df39500a37fd8066104bfd02daae9d5c jdk8u172-b01
+78e071b5c0675416e499e26d82903f436de83156 jdk8u172-b02
+f6f4bebcbf4b7df5eca6e253b596851cca18b5c4 jdk8u172-b03
+d7f51a2cb3fac2d3a7a3ebcd55adaf7b251a3973 jdk8u172-b04
diff --git a/jaxws/.hgtags b/jaxws/.hgtags
index e98b87e..c4d5b65 100644
--- a/jaxws/.hgtags
+++ b/jaxws/.hgtags
@@ -829,3 +829,9 @@
 294248d232cf45819af0d15000b0e172953f3fa9 jdk8u171-b02
 2e4cccb6df4802405c21078b905f9c9db74fea04 jdk8u171-b03
 068b0c57acac24edcf925e3cca73afe671ed7cac jdk8u171-b04
+8479be9da1fa9572a36adcfce19bd36579c9c37c jdk8u171-b05
+16be4c9dff93fdcdb2b705680b641e26320cfd5a jdk8u172-b00
+c4309a2d981b00619635888a63a75b1f32f34555 jdk8u172-b01
+703e4709edae7f83c3794009954f453d6f3706e8 jdk8u172-b02
+b327c90d911f7ad1cfdf32cc18c5f32514b9ce2f jdk8u172-b03
+e9368eb17ab6b839b20f4ff6bd657329aac788b4 jdk8u172-b04
diff --git a/jdk/.hgtags b/jdk/.hgtags
index 5636a6e..0988e6f 100644
--- a/jdk/.hgtags
+++ b/jdk/.hgtags
@@ -862,3 +862,9 @@
 cac020298633fc736f5e21afddf00145665ef0a7 jdk8u171-b02
 c260afc0c5a13407aad4f066f81fba814bb0cbae jdk8u171-b03
 ac700f67341a20ddae093c319da1c65e41edcacd jdk8u171-b04
+863ef3413aa42c15fbdc14fef6732f2741f97046 jdk8u171-b05
+64df143be721d3ef031d765d86277c1e114d627a jdk8u172-b00
+25f7b0cd25cf13106783050fc8e6f4a78487a7bd jdk8u172-b01
+db8272cb8c99eea536a66c4c368c4bf2bf013a81 jdk8u172-b02
+bd24ee3a9a0494121fd1d96c308b9738f585001b jdk8u172-b03
+cf952b84daa1e74403a4d1df541c0ecca830717d jdk8u172-b04
diff --git a/jdk/make/lib/ServiceabilityLibraries.gmk b/jdk/make/lib/ServiceabilityLibraries.gmk
index bd31a44..31ffff6 100644
--- a/jdk/make/lib/ServiceabilityLibraries.gmk
+++ b/jdk/make/lib/ServiceabilityLibraries.gmk
@@ -290,6 +290,10 @@
 BUILD_LIBMANAGEMENT_SRC += $(JDK_TOPDIR)/src/share/native/sun/management \
     $(JDK_TOPDIR)/src/$(OPENJDK_TARGET_OS_API_DIR)/native/sun/management
 
+ifeq ($(OPENJDK_TARGET_OS),aix)
+  BUILD_LIBMANAGEMENT_SRC += $(JDK_TOPDIR)/src/aix/native/sun/management
+endif
+
 BUILD_LIBMANAGEMENT_EXCLUDES :=
 
 BUILD_LIBMANAGEMENT_CFLAGS += -I$(JDK_TOPDIR)/src/share/native/sun/management
diff --git a/jdk/src/aix/native/sun/management/AixOperatingSystem.c b/jdk/src/aix/native/sun/management/AixOperatingSystem.c
new file mode 100644
index 0000000..d8be8ea
--- /dev/null
+++ b/jdk/src/aix/native/sun/management/AixOperatingSystem.c
@@ -0,0 +1,41 @@
+/*
+ * Copyright (c) 2011, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright 2017 SAP SE. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * 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.
+ */
+
+#include "sun_management_OperatingSystemImpl.h"
+
+JNIEXPORT jdouble JNICALL
+Java_sun_management_OperatingSystemImpl_getSystemCpuLoad
+(JNIEnv *env, jobject dummy)
+{
+  return -1.0;
+}
+
+JNIEXPORT jdouble JNICALL
+Java_sun_management_OperatingSystemImpl_getProcessCpuLoad
+(JNIEnv *env, jobject dummy)
+{
+  return -1.0;
+}
diff --git a/jdk/src/macosx/classes/sun/lwawt/LWLightweightFramePeer.java b/jdk/src/macosx/classes/sun/lwawt/LWLightweightFramePeer.java
index 4491b7c..d3ad7bf 100644
--- a/jdk/src/macosx/classes/sun/lwawt/LWLightweightFramePeer.java
+++ b/jdk/src/macosx/classes/sun/lwawt/LWLightweightFramePeer.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -34,10 +34,11 @@
 
 import sun.awt.CausedFocusEvent;
 import sun.awt.LightweightFrame;
+import sun.awt.OverrideNativeWindowHandle;
 import sun.swing.JLightweightFrame;
 import sun.swing.SwingAccessor;
 
-public class LWLightweightFramePeer extends LWWindowPeer {
+public class LWLightweightFramePeer extends LWWindowPeer implements OverrideNativeWindowHandle {
 
     public LWLightweightFramePeer(LightweightFrame target,
                                   PlatformComponent platformComponent,
@@ -116,4 +117,16 @@
     public void updateCursorImmediately() {
         SwingAccessor.getJLightweightFrameAccessor().updateCursor((JLightweightFrame)getLwTarget());
     }
+
+    // SwingNode
+    private volatile long overriddenWindowHandle = 0L;
+
+    @Override
+    public void overrideWindowHandle(final long handle) {
+        this.overriddenWindowHandle = handle;
+    }
+
+    public long getOverriddenWindowHandle() {
+        return overriddenWindowHandle;
+    }
 }
diff --git a/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java b/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java
index b2b4c16..eeb82d3 100644
--- a/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java
@@ -46,6 +46,7 @@
 import sun.awt.AWTAccessor.WindowAccessor;
 import sun.java2d.SurfaceData;
 import sun.java2d.opengl.CGLSurfaceData;
+import sun.lwawt.LWLightweightFramePeer;
 import sun.lwawt.*;
 import sun.util.logging.PlatformLogger;
 
@@ -584,6 +585,20 @@
                     if (!isKeyWindow) {
                         CWrapper.NSWindow.makeKeyWindow(ptr);
                     }
+
+                    if (owner != null
+                            && owner.getPeer() instanceof LWLightweightFramePeer) {
+                        LWLightweightFramePeer peer =
+                                (LWLightweightFramePeer) owner.getPeer();
+
+                        long ownerWindowPtr = peer.getOverriddenWindowHandle();
+                        if (ownerWindowPtr != 0) {
+                            //Place window above JavaFX stage
+                            CWrapper.NSWindow.addChildWindow(
+                                    ownerWindowPtr, ptr,
+                                    CWrapper.NSWindow.NSWindowAbove);
+                        }
+                    }
                 });
             } else {
                 execute(ptr->{
diff --git a/jdk/src/share/classes/com/sun/java/swing/plaf/motif/MotifDesktopIconUI.java b/jdk/src/share/classes/com/sun/java/swing/plaf/motif/MotifDesktopIconUI.java
index a3ce690..cf73a6e 100644
--- a/jdk/src/share/classes/com/sun/java/swing/plaf/motif/MotifDesktopIconUI.java
+++ b/jdk/src/share/classes/com/sun/java/swing/plaf/motif/MotifDesktopIconUI.java
@@ -36,6 +36,8 @@
 import java.util.EventListener;
 import java.io.Serializable;
 
+import sun.awt.AWTAccessor;
+import sun.awt.AWTAccessor.MouseEventAccessor;
 
 /**
  * Motif rendition of the component.
@@ -237,11 +239,15 @@
         }
 
         void forwardEventToParent(MouseEvent e) {
-            getParent().dispatchEvent(new MouseEvent(
+            MouseEvent newEvent = new MouseEvent(
                 getParent(), e.getID(), e.getWhen(), e.getModifiers(),
                 e.getX(), e.getY(), e.getXOnScreen(),
                 e.getYOnScreen(), e.getClickCount(),
-                e.isPopupTrigger(), MouseEvent.NOBUTTON));
+                e.isPopupTrigger(), MouseEvent.NOBUTTON);
+            MouseEventAccessor meAccessor = AWTAccessor.getMouseEventAccessor();
+            meAccessor.setCausedByTouchEvent(newEvent,
+                meAccessor.isCausedByTouchEvent(e));
+            getParent().dispatchEvent(newEvent);
         }
 
         public boolean isFocusTraversable() {
@@ -328,10 +334,14 @@
         }
 
         void forwardEventToParent(MouseEvent e) {
-            getParent().dispatchEvent(new MouseEvent(
+            MouseEvent newEvent = new MouseEvent(
                 getParent(), e.getID(), e.getWhen(), e.getModifiers(),
                 e.getX(), e.getY(), e.getXOnScreen(), e.getYOnScreen(),
-                e.getClickCount(), e.isPopupTrigger(), MouseEvent.NOBUTTON ));
+                e.getClickCount(), e.isPopupTrigger(), MouseEvent.NOBUTTON );
+            MouseEventAccessor meAccessor = AWTAccessor.getMouseEventAccessor();
+            meAccessor.setCausedByTouchEvent(newEvent,
+                meAccessor.isCausedByTouchEvent(e));
+            getParent().dispatchEvent(newEvent);
         }
 
         public boolean isFocusTraversable() {
diff --git a/jdk/src/share/classes/com/sun/java/swing/plaf/motif/MotifInternalFrameTitlePane.java b/jdk/src/share/classes/com/sun/java/swing/plaf/motif/MotifInternalFrameTitlePane.java
index 03c9f23..45431ec 100644
--- a/jdk/src/share/classes/com/sun/java/swing/plaf/motif/MotifInternalFrameTitlePane.java
+++ b/jdk/src/share/classes/com/sun/java/swing/plaf/motif/MotifInternalFrameTitlePane.java
@@ -37,6 +37,9 @@
 import java.beans.VetoableChangeListener;
 import java.beans.PropertyVetoException;
 
+import sun.awt.AWTAccessor;
+import sun.awt.AWTAccessor.MouseEventAccessor;
+
 /**
  * Class that manages a Motif title bar
  *
@@ -356,11 +359,15 @@
         }
 
         void forwardEventToParent(MouseEvent e) {
-            getParent().dispatchEvent(new MouseEvent(
+            MouseEvent newEvent = new MouseEvent(
                 getParent(), e.getID(), e.getWhen(), e.getModifiers(),
                 e.getX(), e.getY(),  e.getXOnScreen(),
                 e.getYOnScreen(), e.getClickCount(),
-                e.isPopupTrigger(),  MouseEvent.NOBUTTON));
+                e.isPopupTrigger(),  MouseEvent.NOBUTTON);
+            MouseEventAccessor meAccessor = AWTAccessor.getMouseEventAccessor();
+            meAccessor.setCausedByTouchEvent(newEvent,
+                meAccessor.isCausedByTouchEvent(e));
+            getParent().dispatchEvent(newEvent);
         }
 
         public void paintComponent(Graphics g) {
diff --git a/jdk/src/share/classes/java/awt/Component.java b/jdk/src/share/classes/java/awt/Component.java
index 516c6fd..314fb6f 100644
--- a/jdk/src/share/classes/java/awt/Component.java
+++ b/jdk/src/share/classes/java/awt/Component.java
@@ -4965,6 +4965,12 @@
                 tpeer.handleEvent(e);
             }
         }
+
+        if (SunToolkit.isTouchKeyboardAutoShowEnabled() &&
+            (toolkit instanceof SunToolkit) &&
+            ((e instanceof MouseEvent) || (e instanceof FocusEvent))) {
+            ((SunToolkit)toolkit).showOrHideTouchKeyboard(this, e);
+        }
     } // dispatchEventImpl()
 
     /*
diff --git a/jdk/src/share/classes/java/awt/Container.java b/jdk/src/share/classes/java/awt/Container.java
index 8525f3c..2766591 100644
--- a/jdk/src/share/classes/java/awt/Container.java
+++ b/jdk/src/share/classes/java/awt/Container.java
@@ -56,6 +56,7 @@
 
 import sun.awt.AppContext;
 import sun.awt.AWTAccessor;
+import sun.awt.AWTAccessor.MouseEventAccessor;
 import sun.awt.CausedFocusEvent;
 import sun.awt.PeerEvent;
 import sun.awt.SunToolkit;
@@ -4777,6 +4778,9 @@
                                srcEvent.getClickCount(),
                                srcEvent.isPopupTrigger(),
                                srcEvent.getButton());
+            MouseEventAccessor meAccessor = AWTAccessor.getMouseEventAccessor();
+            meAccessor.setCausedByTouchEvent(me,
+                meAccessor.isCausedByTouchEvent(srcEvent));
             ((AWTEvent)srcEvent).copyPrivateDataInto(me);
             // translate coordinates to this native container
             final Point ptSrcOrigin = srcComponent.getLocationOnScreen();
@@ -4877,6 +4881,9 @@
                                             e.getClickCount(),
                                             e.isPopupTrigger(),
                                             e.getButton());
+                MouseEventAccessor meAccessor = AWTAccessor.getMouseEventAccessor();
+                meAccessor.setCausedByTouchEvent(retargeted,
+                    meAccessor.isCausedByTouchEvent(e));
             }
 
             ((AWTEvent)e).copyPrivateDataInto(retargeted);
diff --git a/jdk/src/share/classes/java/awt/event/MouseEvent.java b/jdk/src/share/classes/java/awt/event/MouseEvent.java
index 05bec71..3288ce1 100644
--- a/jdk/src/share/classes/java/awt/event/MouseEvent.java
+++ b/jdk/src/share/classes/java/awt/event/MouseEvent.java
@@ -33,6 +33,8 @@
 import java.io.ObjectInputStream;
 import java.awt.IllegalComponentStateException;
 import java.awt.MouseInfo;
+
+import sun.awt.AWTAccessor;
 import sun.awt.SunToolkit;
 
 /**
@@ -332,6 +334,11 @@
     int clickCount;
 
     /**
+     * Indicates whether the event is a result of a touch event.
+     */
+    private boolean causedByTouchEvent;
+
+    /**
      * Indicates which, if any, of the mouse buttons has changed state.
      *
      * The valid values are ranged from 0 to the value returned by the
@@ -399,6 +406,17 @@
             //whatever besides SunToolkit) could also operate.
             cachedNumberOfButtons = 3;
         }
+        AWTAccessor.setMouseEventAccessor(
+            new AWTAccessor.MouseEventAccessor() {
+                public boolean isCausedByTouchEvent(MouseEvent ev) {
+                    return ev.causedByTouchEvent;
+                }
+
+                public void setCausedByTouchEvent(MouseEvent ev,
+                    boolean causedByTouchEvent) {
+                    ev.causedByTouchEvent = causedByTouchEvent;
+                }
+            });
     }
 
     /**
diff --git a/jdk/src/share/classes/java/lang/ApplicationShutdownHooks.java b/jdk/src/share/classes/java/lang/ApplicationShutdownHooks.java
index 512cfc1..df067bc 100644
--- a/jdk/src/share/classes/java/lang/ApplicationShutdownHooks.java
+++ b/jdk/src/share/classes/java/lang/ApplicationShutdownHooks.java
@@ -102,9 +102,13 @@
             hook.start();
         }
         for (Thread hook : threads) {
-            try {
-                hook.join();
-            } catch (InterruptedException x) { }
+            while (true) {
+                try {
+                    hook.join();
+                    break;
+                } catch (InterruptedException ignored) {
+                }
+            }
         }
     }
 }
diff --git a/jdk/src/share/classes/java/lang/ref/Finalizer.java b/jdk/src/share/classes/java/lang/ref/Finalizer.java
index 6ae2262..5cc0ac7 100644
--- a/jdk/src/share/classes/java/lang/ref/Finalizer.java
+++ b/jdk/src/share/classes/java/lang/ref/Finalizer.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -82,6 +82,10 @@
         add();
     }
 
+    static ReferenceQueue<Object> getQueue() {
+        return queue;
+    }
+
     /* Invoked by VM */
     static void register(Object finalizee) {
         new Finalizer(finalizee);
diff --git a/jdk/src/share/classes/java/lang/ref/FinalizerHistogram.java b/jdk/src/share/classes/java/lang/ref/FinalizerHistogram.java
new file mode 100644
index 0000000..195eb48
--- /dev/null
+++ b/jdk/src/share/classes/java/lang/ref/FinalizerHistogram.java
@@ -0,0 +1,80 @@
+/*
+ * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package java.lang.ref;
+
+
+import java.util.Map;
+import java.util.HashMap;
+import java.util.Arrays;
+import java.util.Comparator;
+
+/**
+ * This FinalizerHistogram class is for GC.finalizer_info diagnostic command support.
+ * It is invoked by the VM.
+ */
+
+final class FinalizerHistogram {
+
+    private static final class Entry {
+        private int instanceCount;
+        private final String className;
+
+        int getInstanceCount() {
+            return instanceCount;
+        }
+
+        void increment() {
+            instanceCount += 1;
+        }
+
+        Entry(String className) {
+            this.className = className;
+        }
+    }
+
+    // Method below is called by VM and VM expect certain
+    // entry class layout.
+
+    static Entry[] getFinalizerHistogram() {
+        Map<String, Entry> countMap = new HashMap<>();
+        ReferenceQueue<Object> queue = Finalizer.getQueue();
+        queue.forEach(r -> {
+            Object referent = r.get();
+            if (referent != null) {
+                countMap.computeIfAbsent(
+                    referent.getClass().getName(), Entry::new).increment();
+                /* Clear stack slot containing this variable, to decrease
+                   the chances of false retention with a conservative GC */
+                referent = null;
+            }
+        });
+
+        Entry fhe[] = countMap.values().toArray(new Entry[countMap.size()]);
+        Arrays.sort(fhe,
+                Comparator.comparingInt(Entry::getInstanceCount).reversed());
+        return fhe;
+    }
+}
diff --git a/jdk/src/share/classes/java/lang/ref/Reference.java b/jdk/src/share/classes/java/lang/ref/Reference.java
index 5febcae..f8fa46f 100644
--- a/jdk/src/share/classes/java/lang/ref/Reference.java
+++ b/jdk/src/share/classes/java/lang/ref/Reference.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -99,7 +99,7 @@
      *    Inactive:   this
      */
     @SuppressWarnings("rawtypes")
-    Reference next;
+    volatile Reference next;
 
     /* When active:   next element in a discovered reference list maintained by GC (or this if last)
      *     pending:   next element in the pending list (or null if last)
diff --git a/jdk/src/share/classes/java/lang/ref/ReferenceQueue.java b/jdk/src/share/classes/java/lang/ref/ReferenceQueue.java
index 534d21c..59c5ea8 100644
--- a/jdk/src/share/classes/java/lang/ref/ReferenceQueue.java
+++ b/jdk/src/share/classes/java/lang/ref/ReferenceQueue.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,6 +25,8 @@
 
 package java.lang.ref;
 
+import java.util.function.Consumer;
+
 /**
  * Reference queues, to which registered reference objects are appended by the
  * garbage collector after the appropriate reachability changes are detected.
@@ -75,13 +77,12 @@
         }
     }
 
-    @SuppressWarnings("unchecked")
     private Reference<? extends T> reallyPoll() {       /* Must hold lock */
         Reference<? extends T> r = head;
         if (r != null) {
-            head = (r.next == r) ?
-                null :
-                r.next; // Unchecked due to the next field having a raw type in Reference
+            @SuppressWarnings("unchecked")
+            Reference<? extends T> rn = r.next;
+            head = (rn == r) ? null : rn;
             r.queue = NULL;
             r.next = r;
             queueLength--;
@@ -164,4 +165,32 @@
         return remove(0);
     }
 
+    /**
+     * Iterate queue and invoke given action with each Reference.
+     * Suitable for diagnostic purposes.
+     * WARNING: any use of this method should make sure to not
+     * retain the referents of iterated references (in case of
+     * FinalReference(s)) so that their life is not prolonged more
+     * than necessary.
+     */
+    void forEach(Consumer<? super Reference<? extends T>> action) {
+        for (Reference<? extends T> r = head; r != null;) {
+            action.accept(r);
+            @SuppressWarnings("unchecked")
+            Reference<? extends T> rn = r.next;
+            if (rn == r) {
+                if (r.queue == ENQUEUED) {
+                    // still enqueued -> we reached end of chain
+                    r = null;
+                } else {
+                    // already dequeued: r.queue == NULL; ->
+                    // restart from head when overtaken by queue poller(s)
+                    r = head;
+                }
+            } else {
+                // next in chain
+                r = rn;
+            }
+        }
+    }
 }
diff --git a/jdk/src/share/classes/java/security/ProtectionDomain.java b/jdk/src/share/classes/java/security/ProtectionDomain.java
index 9e597bc..7a86115 100644
--- a/jdk/src/share/classes/java/security/ProtectionDomain.java
+++ b/jdk/src/share/classes/java/security/ProtectionDomain.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,27 +25,21 @@
 
 package java.security;
 
-import java.lang.ref.Reference;
-import java.lang.ref.ReferenceQueue;
-import java.lang.ref.SoftReference;
-import java.lang.ref.WeakReference;
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.Enumeration;
 import java.util.List;
 import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
+import java.util.WeakHashMap;
+import sun.misc.JavaSecurityAccess;
 import sun.misc.JavaSecurityProtectionDomainAccess;
 import static sun.misc.JavaSecurityProtectionDomainAccess.ProtectionDomainCache;
+import sun.misc.SharedSecrets;
 import sun.security.util.Debug;
 import sun.security.util.SecurityConstants;
-import sun.misc.JavaSecurityAccess;
-import sun.misc.SharedSecrets;
 
 /**
- *
- *<p>
- * This ProtectionDomain class encapsulates the characteristics of a domain,
+ * The ProtectionDomain class encapsulates the characteristics of a domain,
  * which encloses a set of classes whose instances are granted a set
  * of permissions when being executed on behalf of a given set of Principals.
  * <p>
@@ -460,14 +454,25 @@
     /**
      * Used for storing ProtectionDomains as keys in a Map.
      */
-    static final class Key {}
+    final class Key {}
 
     static {
         SharedSecrets.setJavaSecurityProtectionDomainAccess(
             new JavaSecurityProtectionDomainAccess() {
                 @Override
                 public ProtectionDomainCache getProtectionDomainCache() {
-                    return new PDCache();
+                    return new ProtectionDomainCache() {
+                        private final Map<Key, PermissionCollection> map =
+                            Collections.synchronizedMap
+                                (new WeakHashMap<Key, PermissionCollection>());
+                        public void put(ProtectionDomain pd,
+                            PermissionCollection pc) {
+                            map.put((pd == null ? null : pd.key), pc);
+                        }
+                        public PermissionCollection get(ProtectionDomain pd) {
+                            return pd == null ? map.get(null) : map.get(pd.key);
+                        }
+                    };
                 }
 
                 @Override
@@ -476,119 +481,4 @@
                 }
             });
     }
-
-    /**
-     * A cache of ProtectionDomains and their Permissions.
-     *
-     * This class stores ProtectionDomains as weak keys in a ConcurrentHashMap
-     * with additional support for checking and removing weak keys that are no
-     * longer in use. There can be cases where the permission collection may
-     * have a chain of strong references back to the ProtectionDomain, which
-     * ordinarily would prevent the entry from being removed from the map. To
-     * address that, we wrap the permission collection in a SoftReference so
-     * that it can be reclaimed by the garbage collector due to memory demand.
-     */
-    private static class PDCache implements ProtectionDomainCache {
-        private final ConcurrentHashMap<WeakProtectionDomainKey,
-                                        SoftReference<PermissionCollection>>
-                                        pdMap = new ConcurrentHashMap<>();
-        private final ReferenceQueue<Key> queue = new ReferenceQueue<>();
-
-        @Override
-        public void put(ProtectionDomain pd, PermissionCollection pc) {
-            processQueue(queue, pdMap);
-            WeakProtectionDomainKey weakPd =
-                new WeakProtectionDomainKey(pd, queue);
-            pdMap.put(weakPd, new SoftReference<>(pc));
-        }
-
-        @Override
-        public PermissionCollection get(ProtectionDomain pd) {
-            processQueue(queue, pdMap);
-            WeakProtectionDomainKey weakPd = new WeakProtectionDomainKey(pd);
-            SoftReference<PermissionCollection> sr = pdMap.get(weakPd);
-            return (sr == null) ? null : sr.get();
-        }
-
-        /**
-         * Removes weak keys from the map that have been enqueued
-         * on the reference queue and are no longer in use.
-         */
-        private static void processQueue(ReferenceQueue<Key> queue,
-                                         ConcurrentHashMap<? extends
-                                         WeakReference<Key>, ?> pdMap) {
-            Reference<? extends Key> ref;
-            while ((ref = queue.poll()) != null) {
-                pdMap.remove(ref);
-            }
-        }
-    }
-
-    /**
-     * A weak key for a ProtectionDomain.
-     */
-    private static class WeakProtectionDomainKey extends WeakReference<Key> {
-        /**
-         * Saved value of the referent's identity hash code, to maintain
-         * a consistent hash code after the referent has been cleared
-         */
-        private final int hash;
-
-        /**
-         * A key representing a null ProtectionDomain.
-         */
-        private static final Key NULL_KEY = new Key();
-
-        /**
-         * Create a new WeakProtectionDomain with the specified domain and
-         * registered with a queue.
-         */
-        WeakProtectionDomainKey(ProtectionDomain pd, ReferenceQueue<Key> rq) {
-            this((pd == null ? NULL_KEY : pd.key), rq);
-        }
-
-        WeakProtectionDomainKey(ProtectionDomain pd) {
-            this(pd == null ? NULL_KEY : pd.key);
-        }
-
-        private WeakProtectionDomainKey(Key key, ReferenceQueue<Key> rq) {
-            super(key, rq);
-            hash = key.hashCode();
-        }
-
-        private WeakProtectionDomainKey(Key key) {
-            super(key);
-            hash = key.hashCode();
-        }
-
-        /**
-         * Returns the identity hash code of the original referent.
-         */
-        @Override
-        public int hashCode() {
-            return hash;
-        }
-
-        /**
-         * Returns true if the given object is an identical
-         * WeakProtectionDomainKey instance, or, if this object's referent
-         * has not been cleared and the given object is another
-         * WeakProtectionDomainKey instance with an identical non-null
-         * referent as this one.
-         */
-        @Override
-        public boolean equals(Object obj) {
-            if (obj == this) {
-                return true;
-            }
-
-            if (obj instanceof WeakProtectionDomainKey) {
-                Object referent = get();
-                return (referent != null) &&
-                       (referent == ((WeakProtectionDomainKey)obj).get());
-            } else {
-                return false;
-            }
-        }
-    }
 }
diff --git a/jdk/src/share/classes/java/text/DecimalFormat.java b/jdk/src/share/classes/java/text/DecimalFormat.java
index a0020ba..2b30a75 100644
--- a/jdk/src/share/classes/java/text/DecimalFormat.java
+++ b/jdk/src/share/classes/java/text/DecimalFormat.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -968,7 +968,7 @@
      *     Decimal  : min = 0. max = 3.
      *
      */
-    private void checkAndSetFastPathStatus() {
+    private boolean checkAndSetFastPathStatus() {
 
         boolean fastPathWasOn = isFastPath;
 
@@ -998,12 +998,27 @@
         } else
             isFastPath = false;
 
+        resetFastPathData(fastPathWasOn);
+        fastPathCheckNeeded = false;
+
+        /*
+         * Returns true after successfully checking the fast path condition and
+         * setting the fast path data. The return value is used by the
+         * fastFormat() method to decide whether to call the resetFastPathData
+         * method to reinitialize fast path data or is it already initialized
+         * in this method.
+         */
+        return true;
+    }
+
+    private void resetFastPathData(boolean fastPathWasOn) {
         // Since some instance properties may have changed while still falling
         // in the fast-path case, we need to reinitialize fastPathData anyway.
         if (isFastPath) {
             // We need to instantiate fastPathData if not already done.
-            if (fastPathData == null)
+            if (fastPathData == null) {
                 fastPathData = new FastPathData();
+            }
 
             // Sets up the locale specific constants used when formatting.
             // '0' is our default representation of zero.
@@ -1011,22 +1026,27 @@
             fastPathData.groupingChar = symbols.getGroupingSeparator();
 
             // Sets up fractional constants related to currency/decimal pattern.
-            fastPathData.fractionalMaxIntBound = (isCurrencyFormat) ? 99 : 999;
-            fastPathData.fractionalScaleFactor = (isCurrencyFormat) ? 100.0d : 1000.0d;
+            fastPathData.fractionalMaxIntBound = (isCurrencyFormat)
+                    ? 99 : 999;
+            fastPathData.fractionalScaleFactor = (isCurrencyFormat)
+                    ? 100.0d : 1000.0d;
 
             // Records the need for adding prefix or suffix
-            fastPathData.positiveAffixesRequired =
-                (positivePrefix.length() != 0) || (positiveSuffix.length() != 0);
-            fastPathData.negativeAffixesRequired =
-                (negativePrefix.length() != 0) || (negativeSuffix.length() != 0);
+            fastPathData.positiveAffixesRequired
+                    = (positivePrefix.length() != 0)
+                        || (positiveSuffix.length() != 0);
+            fastPathData.negativeAffixesRequired
+                    = (negativePrefix.length() != 0)
+                        || (negativeSuffix.length() != 0);
 
             // Creates a cached char container for result, with max possible size.
             int maxNbIntegralDigits = 10;
             int maxNbGroups = 3;
-            int containerSize =
-                Math.max(positivePrefix.length(), negativePrefix.length()) +
-                maxNbIntegralDigits + maxNbGroups + 1 + maximumFractionDigits +
-                Math.max(positiveSuffix.length(), negativeSuffix.length());
+            int containerSize
+                    = Math.max(positivePrefix.length(), negativePrefix.length())
+                    + maxNbIntegralDigits + maxNbGroups + 1
+                    + maximumFractionDigits
+                    + Math.max(positiveSuffix.length(), negativeSuffix.length());
 
             fastPathData.fastPathContainer = new char[containerSize];
 
@@ -1038,17 +1058,18 @@
 
             // Sets up fixed index positions for integral and fractional digits.
             // Sets up decimal point in cached result container.
-            int longestPrefixLength =
-                Math.max(positivePrefix.length(), negativePrefix.length());
-            int decimalPointIndex =
-                maxNbIntegralDigits + maxNbGroups + longestPrefixLength;
+            int longestPrefixLength
+                    = Math.max(positivePrefix.length(),
+                            negativePrefix.length());
+            int decimalPointIndex
+                    = maxNbIntegralDigits + maxNbGroups + longestPrefixLength;
 
-            fastPathData.integralLastIndex    = decimalPointIndex - 1;
+            fastPathData.integralLastIndex = decimalPointIndex - 1;
             fastPathData.fractionalFirstIndex = decimalPointIndex + 1;
-            fastPathData.fastPathContainer[decimalPointIndex] =
-                isCurrencyFormat ?
-                symbols.getMonetaryDecimalSeparator() :
-                symbols.getDecimalSeparator();
+            fastPathData.fastPathContainer[decimalPointIndex]
+                    = isCurrencyFormat
+                            ? symbols.getMonetaryDecimalSeparator()
+                            : symbols.getDecimalSeparator();
 
         } else if (fastPathWasOn) {
             // Previous state was fast-path and is no more.
@@ -1059,8 +1080,6 @@
             fastPathData.charsPositivePrefix = null;
             fastPathData.charsNegativePrefix = null;
         }
-
-        fastPathCheckNeeded = false;
     }
 
     /**
@@ -1554,9 +1573,11 @@
      * @return the formatted result for {@code d} as a string.
      */
     String fastFormat(double d) {
+        boolean isDataSet = false;
         // (Re-)Evaluates fast-path status if needed.
-        if (fastPathCheckNeeded)
-            checkAndSetFastPathStatus();
+        if (fastPathCheckNeeded) {
+            isDataSet = checkAndSetFastPathStatus();
+        }
 
         if (!isFastPath )
             // DecimalFormat instance is not in a fast-path state.
@@ -1580,9 +1601,21 @@
         if (d > MAX_INT_AS_DOUBLE)
             // Filters out values that are outside expected fast-path range
             return null;
-        else
+        else {
+            if (!isDataSet) {
+                /*
+                 * If the fast path data is not set through
+                 * checkAndSetFastPathStatus() and fulfil the
+                 * fast path conditions then reset the data
+                 * directly through resetFastPathData()
+                 */
+                resetFastPathData(isFastPath);
+            }
             fastDoubleFormat(d, negative);
 
+        }
+
+
         // Returns a new string from updated fastPathContainer.
         return new String(fastPathData.fastPathContainer,
                           fastPathData.firstUsedIndex,
diff --git a/jdk/src/share/classes/javax/swing/Autoscroller.java b/jdk/src/share/classes/javax/swing/Autoscroller.java
index 6def237..dc15815 100644
--- a/jdk/src/share/classes/javax/swing/Autoscroller.java
+++ b/jdk/src/share/classes/javax/swing/Autoscroller.java
@@ -28,6 +28,9 @@
 import java.awt.*;
 import java.awt.event.*;
 
+import sun.awt.AWTAccessor;
+import sun.awt.AWTAccessor.MouseEventAccessor;
+
 /**
  * Autoscroller is responsible for generating synthetic mouse dragged
  * events. It is the responsibility of the Component (or its MouseListeners)
@@ -96,6 +99,9 @@
                                e.getYOnScreen(),
                                e.getClickCount(), e.isPopupTrigger(),
                                MouseEvent.NOBUTTON);
+        MouseEventAccessor meAccessor = AWTAccessor.getMouseEventAccessor();
+        meAccessor.setCausedByTouchEvent(event,
+            meAccessor.isCausedByTouchEvent(e));
 
         if (timer == null) {
             timer = new Timer(100, this);
@@ -173,6 +179,9 @@
                                       event.getClickCount(),
                                       event.isPopupTrigger(),
                                       MouseEvent.NOBUTTON);
+        MouseEventAccessor meAccessor = AWTAccessor.getMouseEventAccessor();
+        meAccessor.setCausedByTouchEvent(e,
+            meAccessor.isCausedByTouchEvent(event));
         component.superProcessMouseMotionEvent(e);
     }
 
diff --git a/jdk/src/share/classes/javax/swing/JList.java b/jdk/src/share/classes/javax/swing/JList.java
index fc2499d..7dbaec1 100644
--- a/jdk/src/share/classes/javax/swing/JList.java
+++ b/jdk/src/share/classes/javax/swing/JList.java
@@ -48,6 +48,8 @@
 import java.io.IOException;
 import java.io.Serializable;
 
+import sun.awt.AWTAccessor;
+import sun.awt.AWTAccessor.MouseEventAccessor;
 import sun.swing.SwingUtilities2;
 import sun.swing.SwingUtilities2.Section;
 import static sun.swing.SwingUtilities2.Section.*;
@@ -1553,6 +1555,10 @@
                                               event.getClickCount(),
                                               event.isPopupTrigger(),
                                               MouseEvent.NOBUTTON);
+                    MouseEventAccessor meAccessor =
+                        AWTAccessor.getMouseEventAccessor();
+                    meAccessor.setCausedByTouchEvent(newEvent,
+                        meAccessor.isCausedByTouchEvent(event));
 
                     String tip = ((JComponent)rComponent).getToolTipText(
                                               newEvent);
diff --git a/jdk/src/share/classes/javax/swing/JTable.java b/jdk/src/share/classes/javax/swing/JTable.java
index 3626bd8..4d7363f 100644
--- a/jdk/src/share/classes/javax/swing/JTable.java
+++ b/jdk/src/share/classes/javax/swing/JTable.java
@@ -51,6 +51,9 @@
 
 import javax.print.attribute.*;
 import javax.print.PrintService;
+
+import sun.awt.AWTAccessor;
+import sun.awt.AWTAccessor.MouseEventAccessor;
 import sun.reflect.misc.ReflectUtil;
 
 import sun.swing.SwingUtilities2;
@@ -3404,6 +3407,9 @@
                                           event.getClickCount(),
                                           event.isPopupTrigger(),
                                           MouseEvent.NOBUTTON);
+                MouseEventAccessor meAccessor = AWTAccessor.getMouseEventAccessor();
+                meAccessor.setCausedByTouchEvent(newEvent,
+                    meAccessor.isCausedByTouchEvent(event));
 
                 tip = ((JComponent)component).getToolTipText(newEvent);
             }
diff --git a/jdk/src/share/classes/javax/swing/JTree.java b/jdk/src/share/classes/javax/swing/JTree.java
index bd1e9c5..9763440 100644
--- a/jdk/src/share/classes/javax/swing/JTree.java
+++ b/jdk/src/share/classes/javax/swing/JTree.java
@@ -35,6 +35,9 @@
 import javax.swing.tree.*;
 import javax.swing.text.Position;
 import javax.accessibility.*;
+
+import sun.awt.AWTAccessor;
+import sun.awt.AWTAccessor.MouseEventAccessor;
 import sun.swing.SwingUtilities2;
 import sun.swing.SwingUtilities2.Section;
 import static sun.swing.SwingUtilities2.Section.*;
@@ -1562,6 +1565,10 @@
                                               event.getClickCount(),
                                               event.isPopupTrigger(),
                                               MouseEvent.NOBUTTON);
+                    MouseEventAccessor meAccessor =
+                        AWTAccessor.getMouseEventAccessor();
+                    meAccessor.setCausedByTouchEvent(newEvent,
+                        meAccessor.isCausedByTouchEvent(event));
 
                     tip = ((JComponent)rComponent).getToolTipText(newEvent);
                 }
diff --git a/jdk/src/share/classes/javax/swing/MenuSelectionManager.java b/jdk/src/share/classes/javax/swing/MenuSelectionManager.java
index 3f83acb..cba0801 100644
--- a/jdk/src/share/classes/javax/swing/MenuSelectionManager.java
+++ b/jdk/src/share/classes/javax/swing/MenuSelectionManager.java
@@ -30,6 +30,8 @@
 import javax.swing.event.*;
 
 import sun.awt.AppContext;
+import sun.awt.AWTAccessor;
+import sun.awt.AWTAccessor.MouseEventAccessor;
 import sun.swing.SwingUtilities2;
 
 /**
@@ -305,6 +307,9 @@
                                                               event.getClickCount(),
                                                               event.isPopupTrigger(),
                                                               MouseEvent.NOBUTTON);
+                        MouseEventAccessor meAccessor = AWTAccessor.getMouseEventAccessor();
+                        meAccessor.setCausedByTouchEvent(exitEvent,
+                            meAccessor.isCausedByTouchEvent(event));
                         currentSelection[currentSelection.length-1].
                             processMouseEvent(exitEvent, path, this);
 
@@ -317,6 +322,8 @@
                                                                event.getClickCount(),
                                                                event.isPopupTrigger(),
                                                                MouseEvent.NOBUTTON);
+                        meAccessor.setCausedByTouchEvent(enterEvent,
+                            meAccessor.isCausedByTouchEvent(event));
                         subElements[j].processMouseEvent(enterEvent, path, this);
                     }
                     MouseEvent mouseEvent = new MouseEvent(mc, event.getID(),event. getWhen(),
@@ -326,6 +333,9 @@
                                                            event.getClickCount(),
                                                            event.isPopupTrigger(),
                                                            MouseEvent.NOBUTTON);
+                    MouseEventAccessor meAccessor = AWTAccessor.getMouseEventAccessor();
+                    meAccessor.setCausedByTouchEvent(mouseEvent,
+                        meAccessor.isCausedByTouchEvent(event));
                     subElements[j].processMouseEvent(mouseEvent, path, this);
                     success = true;
                     event.consume();
diff --git a/jdk/src/share/classes/javax/swing/SwingUtilities.java b/jdk/src/share/classes/javax/swing/SwingUtilities.java
index 7c13765..83f338b 100644
--- a/jdk/src/share/classes/javax/swing/SwingUtilities.java
+++ b/jdk/src/share/classes/javax/swing/SwingUtilities.java
@@ -44,6 +44,8 @@
 import sun.security.action.GetPropertyAction;
 
 import sun.awt.AppContext;
+import sun.awt.AWTAccessor;
+import sun.awt.AWTAccessor.MouseEventAccessor;
 
 /**
  * A collection of utility methods for Swing.
@@ -355,6 +357,9 @@
                                       sourceEvent.getClickCount(),
                                       sourceEvent.isPopupTrigger(),
                                       sourceEvent.getButton());
+            MouseEventAccessor meAccessor = AWTAccessor.getMouseEventAccessor();
+            meAccessor.setCausedByTouchEvent(newEvent,
+                meAccessor.isCausedByTouchEvent(sourceEvent));
         }
         return newEvent;
     }
diff --git a/jdk/src/share/classes/javax/swing/plaf/basic/BasicComboPopup.java b/jdk/src/share/classes/javax/swing/plaf/basic/BasicComboPopup.java
index ae39867..d000400 100644
--- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicComboPopup.java
+++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicComboPopup.java
@@ -36,6 +36,8 @@
 import java.beans.PropertyChangeEvent;
 import java.io.Serializable;
 
+import sun.awt.AWTAccessor;
+import sun.awt.AWTAccessor.MouseEventAccessor;
 
 /**
  * This is a basic implementation of the <code>ComboPopup</code> interface.
@@ -499,13 +501,18 @@
                     // Fix for 4234053. Filter out the Control Key from the list.
                     // ie., don't allow CTRL key deselection.
                     Toolkit toolkit = Toolkit.getDefaultToolkit();
-                    e = new MouseEvent((Component)e.getSource(), e.getID(), e.getWhen(),
+                    MouseEvent newEvent = new MouseEvent(
+                                       (Component)e.getSource(), e.getID(), e.getWhen(),
                                        e.getModifiers() ^ toolkit.getMenuShortcutKeyMask(),
                                        e.getX(), e.getY(),
                                        e.getXOnScreen(), e.getYOnScreen(),
                                        e.getClickCount(),
                                        e.isPopupTrigger(),
                                        MouseEvent.NOBUTTON);
+                    MouseEventAccessor meAccessor = AWTAccessor.getMouseEventAccessor();
+                    meAccessor.setCausedByTouchEvent(newEvent,
+                        meAccessor.isCausedByTouchEvent(e));
+                    e = newEvent;
                 }
                 super.processMouseEvent(e);
             }
@@ -1195,6 +1202,9 @@
                                               e.getClickCount(),
                                               e.isPopupTrigger(),
                                               MouseEvent.NOBUTTON );
+        MouseEventAccessor meAccessor = AWTAccessor.getMouseEventAccessor();
+        meAccessor.setCausedByTouchEvent(newEvent,
+            meAccessor.isCausedByTouchEvent(e));
         return newEvent;
     }
 
diff --git a/jdk/src/share/classes/javax/swing/table/JTableHeader.java b/jdk/src/share/classes/javax/swing/table/JTableHeader.java
index 9def629..479fa39 100644
--- a/jdk/src/share/classes/javax/swing/table/JTableHeader.java
+++ b/jdk/src/share/classes/javax/swing/table/JTableHeader.java
@@ -43,6 +43,8 @@
 import java.io.ObjectInputStream;
 import java.io.IOException;
 
+import sun.awt.AWTAccessor;
+import sun.awt.AWTAccessor.MouseEventAccessor;
 
 /**
  * This is the object which manages the header of the <code>JTable</code>.
@@ -420,6 +422,9 @@
                                           p.x, p.y, event.getXOnScreen(), event.getYOnScreen(),
                                           event.getClickCount(),
                                           event.isPopupTrigger(), MouseEvent.NOBUTTON);
+                MouseEventAccessor meAccessor = AWTAccessor.getMouseEventAccessor();
+                meAccessor.setCausedByTouchEvent(newEvent,
+                    meAccessor.isCausedByTouchEvent(event));
 
                 tip = ((JComponent)component).getToolTipText(newEvent);
             }
diff --git a/jdk/src/share/classes/sun/awt/AWTAccessor.java b/jdk/src/share/classes/sun/awt/AWTAccessor.java
index 45d806b..093fbf3 100644
--- a/jdk/src/share/classes/sun/awt/AWTAccessor.java
+++ b/jdk/src/share/classes/sun/awt/AWTAccessor.java
@@ -34,6 +34,7 @@
 import java.awt.event.InputEvent;
 import java.awt.event.InvocationEvent;
 import java.awt.event.KeyEvent;
+import java.awt.event.MouseEvent;
 import java.awt.geom.Point2D;
 import java.awt.peer.ComponentPeer;
 import java.awt.peer.MenuComponentPeer;
@@ -385,6 +386,21 @@
         int[] getButtonDownMasks();
     }
 
+    /**
+     * An accessor for the MouseEvent class.
+     */
+    public interface MouseEventAccessor {
+        /**
+         * Indicates whether the event is a result of a touch event.
+         */
+        boolean isCausedByTouchEvent(MouseEvent ev);
+
+        /**
+         * Sets whether the event is a result of a touch event.
+         */
+        void setCausedByTouchEvent(MouseEvent ev, boolean causedByTouchEvent);
+    }
+
     /*
      * An accessor for the java.awt.Frame class.
      */
@@ -770,6 +786,7 @@
     private static WindowAccessor windowAccessor;
     private static AWTEventAccessor awtEventAccessor;
     private static InputEventAccessor inputEventAccessor;
+    private static MouseEventAccessor mouseEventAccessor;
     private static FrameAccessor frameAccessor;
     private static KeyboardFocusManagerAccessor kfmAccessor;
     private static MenuComponentAccessor menuComponentAccessor;
@@ -881,6 +898,23 @@
     }
 
     /*
+     * Set an accessor object for the java.awt.event.MouseEvent class.
+     */
+    public static void setMouseEventAccessor(MouseEventAccessor mea) {
+        mouseEventAccessor = mea;
+    }
+
+    /*
+     * Retrieve the accessor object for the java.awt.event.MouseEvent class.
+     */
+    public static MouseEventAccessor getMouseEventAccessor() {
+        if (mouseEventAccessor == null) {
+            unsafe.ensureClassInitialized(MouseEvent.class);
+        }
+        return mouseEventAccessor;
+    }
+
+    /*
      * Set an accessor object for the java.awt.Frame class.
      */
     public static void setFrameAccessor(FrameAccessor fa) {
diff --git a/jdk/src/share/classes/sun/awt/OverrideNativeWindowHandle.java b/jdk/src/share/classes/sun/awt/OverrideNativeWindowHandle.java
new file mode 100644
index 0000000..8ec172b
--- /dev/null
+++ b/jdk/src/share/classes/sun/awt/OverrideNativeWindowHandle.java
@@ -0,0 +1,41 @@
+/*
+ * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package sun.awt;
+
+/**
+ * Used for replacing window owner with another non-Swing window.
+ * It is useful in case of JavaFX-Swing interop:
+ * it helps to keep Swing dialogs above its owner(JavaFX stage).
+ */
+
+public interface OverrideNativeWindowHandle {
+
+    /**
+     * Replaces an owner window with a window with provided handle.
+     * @param handle native window handle
+     */
+    void overrideWindowHandle(final long handle);
+}
diff --git a/jdk/src/share/classes/sun/awt/SunToolkit.java b/jdk/src/share/classes/sun/awt/SunToolkit.java
index 6269645..b872b62 100644
--- a/jdk/src/share/classes/sun/awt/SunToolkit.java
+++ b/jdk/src/share/classes/sun/awt/SunToolkit.java
@@ -70,6 +70,9 @@
         if (AccessController.doPrivileged(new GetBooleanAction("sun.awt.nativedebug"))) {
             DebugSettings.init();
         }
+        touchKeyboardAutoShowIsEnabled = Boolean.valueOf(
+            AccessController.doPrivileged(new GetPropertyAction(
+                "awt.touchKeyboardAutoShowIsEnabled", "true")));
     };
 
     /**
@@ -1707,6 +1710,13 @@
      */
     public abstract void ungrab(Window w);
 
+    public void showOrHideTouchKeyboard(Component comp, AWTEvent e) {}
+
+    private static boolean touchKeyboardAutoShowIsEnabled;
+
+    public static boolean isTouchKeyboardAutoShowEnabled() {
+        return touchKeyboardAutoShowIsEnabled;
+    }
 
     /**
      * Locates the splash screen library in a platform dependent way and closes
diff --git a/jdk/src/share/classes/sun/management/Agent.java b/jdk/src/share/classes/sun/management/Agent.java
index 47734a0..36c2018 100644
--- a/jdk/src/share/classes/sun/management/Agent.java
+++ b/jdk/src/share/classes/sun/management/Agent.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -211,7 +211,7 @@
                 throw new AgentConfigurationError(INVALID_JMXREMOTE_PORT, "No port specified");
             }
         } catch (AgentConfigurationError err) {
-            error(err.getError(), err.getParams());
+            error(err);
         }
     }
 
@@ -266,7 +266,7 @@
             }
 
         } catch (AgentConfigurationError e) {
-            error(e.getError(), e.getParams());
+            error(e);
         } catch (Exception e) {
             error(e);
         }
@@ -496,18 +496,6 @@
         throw new RuntimeException(keyText);
     }
 
-    public static void error(String key, String[] params) {
-        if (params == null || params.length == 0) {
-            error(key);
-        } else {
-            StringBuffer message = new StringBuffer(params[0]);
-            for (int i = 1; i < params.length; i++) {
-                message.append(" " + params[i]);
-            }
-            error(key, message.toString());
-        }
-    }
-
     public static void error(String key, String message) {
         String keyText = getText(key);
         System.err.print(getText("agent.err.error") + ": " + keyText);
@@ -521,6 +509,23 @@
         throw new RuntimeException(e);
     }
 
+    public static void error(AgentConfigurationError e) {
+        String keyText = getText(e.getError());
+        String[] params = e.getParams();
+
+        System.err.print(getText("agent.err.error") + ": " + keyText);
+
+        if (params != null && params.length != 0) {
+           StringBuffer message = new StringBuffer(params[0]);
+           for (int i = 1; i < params.length; i++) {
+               message.append(" " + params[i]);
+           }
+           System.err.println(": " + message);
+        }
+        e.printStackTrace();
+        throw new RuntimeException(e);
+    }
+
     public static void warning(String key, String message) {
         System.err.print(getText("agent.err.warning") + ": " + getText(key));
         System.err.println(": " + message);
diff --git a/jdk/src/share/classes/sun/security/tools/KeyStoreUtil.java b/jdk/src/share/classes/sun/security/tools/KeyStoreUtil.java
index ecfba5f..6407b88 100644
--- a/jdk/src/share/classes/sun/security/tools/KeyStoreUtil.java
+++ b/jdk/src/share/classes/sun/security/tools/KeyStoreUtil.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -63,8 +63,9 @@
      * MSCAPI KeyStores
      */
     public static boolean isWindowsKeyStore(String storetype) {
-        return storetype.equalsIgnoreCase("Windows-MY")
-                || storetype.equalsIgnoreCase("Windows-ROOT");
+        return storetype != null
+                && (storetype.equalsIgnoreCase("Windows-MY")
+                    || storetype.equalsIgnoreCase("Windows-ROOT"));
     }
 
     /**
diff --git a/jdk/src/share/classes/sun/security/tools/keytool/Main.java b/jdk/src/share/classes/sun/security/tools/keytool/Main.java
index fac7b5d..0730f4f 100644
--- a/jdk/src/share/classes/sun/security/tools/keytool/Main.java
+++ b/jdk/src/share/classes/sun/security/tools/keytool/Main.java
@@ -462,12 +462,12 @@
                 passwords.add(storePass);
             } else if (collator.compare(flags, "-storetype") == 0 ||
                     collator.compare(flags, "-deststoretype") == 0) {
-                storetype = args[++i];
+                storetype = KeyStoreUtil.niceStoreTypeName(args[++i]);
             } else if (collator.compare(flags, "-srcstorepass") == 0) {
                 srcstorePass = getPass(modifier, args[++i]);
                 passwords.add(srcstorePass);
             } else if (collator.compare(flags, "-srcstoretype") == 0) {
-                srcstoretype = args[++i];
+                srcstoretype = KeyStoreUtil.niceStoreTypeName(args[++i]);
             } else if (collator.compare(flags, "-srckeypass") == 0) {
                 srckeyPass = getPass(modifier, args[++i]);
                 passwords.add(srckeyPass);
@@ -592,16 +592,6 @@
      * Execute the commands.
      */
     void doCommands(PrintStream out) throws Exception {
-        if (storetype == null) {
-            storetype = KeyStore.getDefaultType();
-        }
-        storetype = KeyStoreUtil.niceStoreTypeName(storetype);
-
-        if (srcstoretype == null) {
-            srcstoretype = KeyStore.getDefaultType();
-        }
-        srcstoretype = KeyStoreUtil.niceStoreTypeName(srcstoretype);
-
         if (P11KEYSTORE.equalsIgnoreCase(storetype) ||
                 KeyStoreUtil.isWindowsKeyStore(storetype)) {
             token = true;
@@ -626,11 +616,6 @@
                         (".storepasswd.and.keypasswd.commands.not.supported.if.storetype.is.{0}"), storetype));
         }
 
-        if (P12KEYSTORE.equalsIgnoreCase(storetype) && command == KEYPASSWD) {
-            throw new UnsupportedOperationException(rb.getString
-                        (".keypasswd.commands.not.supported.if.storetype.is.PKCS12"));
-        }
-
         if (token && (keyPass != null || newPass != null || destKeyPass != null)) {
             throw new IllegalArgumentException(MessageFormat.format(rb.getString
                 (".keypass.and.new.can.not.be.specified.if.storetype.is.{0}"), storetype));
@@ -802,6 +787,9 @@
         }
 
         // Create new keystore
+        if (storetype == null) {
+            storetype = KeyStore.getDefaultType();
+        }
         if (providerName == null) {
             keyStore = KeyStore.getInstance(storetype);
         } else {
@@ -839,6 +827,11 @@
             }
         }
 
+        if (P12KEYSTORE.equalsIgnoreCase(storetype) && command == KEYPASSWD) {
+            throw new UnsupportedOperationException(rb.getString
+                    (".keypasswd.commands.not.supported.if.storetype.is.PKCS12"));
+        }
+
         // All commands that create or modify the keystore require a keystore
         // password.
 
@@ -2014,6 +2007,9 @@
 
         KeyStore store;
         try {
+            if (srcstoretype == null) {
+                srcstoretype = KeyStore.getDefaultType();
+            }
             if (srcProviderName == null) {
                 store = KeyStore.getInstance(srcstoretype);
             } else {
@@ -2635,12 +2631,12 @@
                     if (rfc) {
                         dumpCert(cert, out);
                     } else {
-                        out.println("Certificate #" + i++);
+                        out.println("Certificate #" + i);
                         out.println("====================================");
                         printX509Cert((X509Certificate)cert, out);
                         out.println();
                     }
-                    checkWeak(oneInMany(rb.getString("the.certificate"), i, chain.size()), cert);
+                    checkWeak(oneInMany(rb.getString("the.certificate"), i++, chain.size()), cert);
                 } catch (Exception e) {
                     if (debug) {
                         e.printStackTrace();
diff --git a/jdk/src/share/classes/sun/swing/FilePane.java b/jdk/src/share/classes/sun/swing/FilePane.java
index 9ae60b5..b538bd1 100644
--- a/jdk/src/share/classes/sun/swing/FilePane.java
+++ b/jdk/src/share/classes/sun/swing/FilePane.java
@@ -44,6 +44,8 @@
 import javax.swing.table.*;
 import javax.swing.text.*;
 
+import sun.awt.AWTAccessor;
+import sun.awt.AWTAccessor.MouseEventAccessor;
 import sun.awt.shell.*;
 
 /**
@@ -1835,13 +1837,17 @@
                     // Make a new event with the list as source, placing the
                     // click in the corresponding list cell.
                     Rectangle r = list.getCellBounds(index, index);
-                    evt = new MouseEvent(list, evt.getID(),
+                    MouseEvent newEvent = new MouseEvent(list, evt.getID(),
                                          evt.getWhen(), evt.getModifiers(),
                                          r.x + 1, r.y + r.height/2,
                                          evt.getXOnScreen(),
                                          evt.getYOnScreen(),
                                          evt.getClickCount(), evt.isPopupTrigger(),
                                          evt.getButton());
+                    MouseEventAccessor meAccessor = AWTAccessor.getMouseEventAccessor();
+                    meAccessor.setCausedByTouchEvent(newEvent,
+                        meAccessor.isCausedByTouchEvent(evt));
+                    evt = newEvent;
                 }
             } else {
                 return;
diff --git a/jdk/src/share/classes/sun/swing/JLightweightFrame.java b/jdk/src/share/classes/sun/swing/JLightweightFrame.java
index c8882e4..1fad9b4 100644
--- a/jdk/src/share/classes/sun/swing/JLightweightFrame.java
+++ b/jdk/src/share/classes/sun/swing/JLightweightFrame.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -61,8 +61,10 @@
 import javax.swing.RootPaneContainer;
 import javax.swing.SwingUtilities;
 
+import sun.awt.AWTAccessor;
 import sun.awt.DisplayChangedListener;
 import sun.awt.LightweightFrame;
+import sun.awt.OverrideNativeWindowHandle;
 import sun.security.action.GetPropertyAction;
 import sun.swing.SwingUtilities2.RepaintListener;
 
@@ -478,6 +480,17 @@
         }
     }
 
+    //Called by reflection by SwingNode
+    public void overrideNativeWindowHandle(long handle, Runnable closeWindow) {
+        final Object peer = AWTAccessor.getComponentAccessor().getPeer(this);
+        if (peer instanceof OverrideNativeWindowHandle) {
+            ((OverrideNativeWindowHandle) peer).overrideWindowHandle(handle);
+        }
+        if (closeWindow != null) {
+            closeWindow.run();
+        }
+    }
+
     public <T extends DragGestureRecognizer> T createDragGestureRecognizer(
             Class<T> abstractRecognizerClass,
             DragSource ds, Component c, int srcActions,
diff --git a/jdk/src/share/sample/scripting/scriptpad/src/scripts/memory.sh b/jdk/src/share/sample/scripting/scriptpad/src/scripts/memory.sh
index 8da155b..6a1ece6 100644
--- a/jdk/src/share/sample/scripting/scriptpad/src/scripts/memory.sh
+++ b/jdk/src/share/sample/scripting/scriptpad/src/scripts/memory.sh
@@ -1,3 +1,4 @@
+#!/bin/sh
 #
 # Copyright (c) 2006, 2013, Oracle and/or its affiliates. All rights reserved.
 #
diff --git a/jdk/src/solaris/classes/sun/awt/X11/XLightweightFramePeer.java b/jdk/src/solaris/classes/sun/awt/X11/XLightweightFramePeer.java
index 05e7573..677c14b 100644
--- a/jdk/src/solaris/classes/sun/awt/X11/XLightweightFramePeer.java
+++ b/jdk/src/solaris/classes/sun/awt/X11/XLightweightFramePeer.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -29,10 +29,11 @@
 import java.awt.dnd.DropTarget;
 
 import sun.awt.LightweightFrame;
+import sun.awt.OverrideNativeWindowHandle;
 import sun.swing.JLightweightFrame;
 import sun.swing.SwingAccessor;
 
-public class XLightweightFramePeer extends XFramePeer {
+public class XLightweightFramePeer extends XFramePeer implements OverrideNativeWindowHandle {
 
     XLightweightFramePeer(LightweightFrame target) {
         super(target);
@@ -80,4 +81,15 @@
     public void removeDropTarget(DropTarget dt) {
         getLwTarget().removeDropTarget(dt);
     }
+
+    private volatile long overriddenWindowHandle = 0L;
+
+    @Override
+    public void overrideWindowHandle(final long handle) {
+        overriddenWindowHandle = handle;
+    }
+
+    public long getOverriddenWindowHandle() {
+        return overriddenWindowHandle;
+    }
 }
diff --git a/jdk/src/solaris/classes/sun/awt/X11/XWindowPeer.java b/jdk/src/solaris/classes/sun/awt/X11/XWindowPeer.java
index 0930293..9eb3259 100644
--- a/jdk/src/solaris/classes/sun/awt/X11/XWindowPeer.java
+++ b/jdk/src/solaris/classes/sun/awt/X11/XWindowPeer.java
@@ -1648,6 +1648,16 @@
         while (!XlibUtil.isToplevelWindow(tpw) && !XlibUtil.isXAWTToplevelWindow(tpw)) {
             tpw = XlibUtil.getParentWindow(tpw);
         }
+
+        XBaseWindow parent = transientForWindow;
+        if (parent instanceof XLightweightFramePeer) {
+            XLightweightFramePeer peer = (XLightweightFramePeer) parent;
+            long ownerWindowPtr = peer.getOverriddenWindowHandle();
+            if (ownerWindowPtr != 0) {
+                tpw = ownerWindowPtr;
+            }
+        }
+
         XlibWrapper.XSetTransientFor(XToolkit.getDisplay(), bpw, tpw);
         window.curRealTransientFor = transientForWindow;
     }
diff --git a/jdk/src/solaris/classes/sun/java2d/xr/XRDrawImage.java b/jdk/src/solaris/classes/sun/java2d/xr/XRDrawImage.java
index ea8edbb..69502f2 100644
--- a/jdk/src/solaris/classes/sun/java2d/xr/XRDrawImage.java
+++ b/jdk/src/solaris/classes/sun/java2d/xr/XRDrawImage.java
@@ -46,24 +46,28 @@
         SurfaceData dstData = sg.surfaceData;
         SurfaceData srcData = dstData.getSourceSurfaceData(img,
                 SunGraphics2D.TRANSFORM_GENERIC, sg.imageComp, bgColor);
-        int compRule = ((AlphaComposite) sg.composite).getRule();
-        float extraAlpha = ((AlphaComposite) sg.composite).getAlpha();
 
-        if (srcData != null && !isBgOperation(srcData, bgColor)
+        if (sg.composite instanceof AlphaComposite) {
+            int compRule = ((AlphaComposite) sg.composite).getRule();
+            float extraAlpha = ((AlphaComposite) sg.composite).getAlpha();
+
+            if (srcData != null && !isBgOperation(srcData, bgColor)
                 && interpType <= AffineTransformOp.TYPE_BILINEAR
                 && (XRUtils.isMaskEvaluated(XRUtils.j2dAlphaCompToXR(compRule))
-                        || (XRUtils.isTransformQuadrantRotated(tx)) && extraAlpha == 1.0f))
-                         {
-            SurfaceType srcType = srcData.getSurfaceType();
-            SurfaceType dstType = dstData.getSurfaceType();
+                    || (XRUtils.isTransformQuadrantRotated(tx))
+                    && extraAlpha == 1.0f))
+            {
+                SurfaceType srcType = srcData.getSurfaceType();
+                SurfaceType dstType = dstData.getSurfaceType();
 
-            TransformBlit blit = TransformBlit.getFromCache(srcType,
-                    sg.imageComp, dstType);
-            if (blit != null) {
-                blit.Transform(srcData, dstData, sg.composite,
-                        sg.getCompClip(), tx, interpType, sx1, sy1, 0, 0, sx2
+                TransformBlit blit = TransformBlit.getFromCache(srcType,
+                        sg.imageComp, dstType);
+                if (blit != null) {
+                    blit.Transform(srcData, dstData, sg.composite,
+                          sg.getCompClip(), tx, interpType, sx1, sy1, 0, 0, sx2
                                 - sx1, sy2 - sy1);
                     return;
+                }
             }
         }
 
diff --git a/jdk/src/solaris/classes/sun/java2d/xr/XRPMBlitLoops.java b/jdk/src/solaris/classes/sun/java2d/xr/XRPMBlitLoops.java
index 6a2f714..a06a312 100644
--- a/jdk/src/solaris/classes/sun/java2d/xr/XRPMBlitLoops.java
+++ b/jdk/src/solaris/classes/sun/java2d/xr/XRPMBlitLoops.java
@@ -127,7 +127,11 @@
             vImgSurfaceType = SurfaceType.IntArgbPre;
         }
 
-        if (vImg == null || vImg.getWidth() < w || vImg.getHeight() < h) {
+        if (vImg == null || vImg.getWidth() < w || vImg.getHeight() < h ||
+            // Sometimes we get volatile image of wrong dest surface type,
+            // so recreating it
+            !(vImg.getDestSurface() instanceof XRSurfaceData))
+        {
             if (vImg != null) {
                 vImg.flush();
             }
@@ -145,6 +149,11 @@
         }
 
         Blit swToSurfaceBlit = Blit.getFromCache(src.getSurfaceType(), CompositeType.SrcNoEa, vImgSurfaceType);
+
+        if (!(vImg.getDestSurface() instanceof XRSurfaceData)) {
+            throw new InvalidPipeException("wrong surface data type: " + vImg.getDestSurface());
+        }
+
         XRSurfaceData vImgSurface = (XRSurfaceData) vImg.getDestSurface();
         swToSurfaceBlit.Blit(src, vImgSurface, AlphaComposite.Src, null,
                              sx, sy, 0, 0, w, h);
diff --git a/jdk/src/windows/classes/sun/awt/windows/WInputMethod.java b/jdk/src/windows/classes/sun/awt/windows/WInputMethod.java
index 343e2a1..3e2fbfa 100644
--- a/jdk/src/windows/classes/sun/awt/windows/WInputMethod.java
+++ b/jdk/src/windows/classes/sun/awt/windows/WInputMethod.java
@@ -493,7 +493,7 @@
             // set Clause and Reading Information
             if (clauseBoundary!=null && clauseReading!=null &&
                 clauseReading.length!=0 && clauseBoundary.length==clauseReading.length+1 &&
-                clauseBoundary[0]==0 && clauseBoundary[clauseReading.length]==text.length() )
+                clauseBoundary[0]==0 && clauseBoundary[clauseReading.length]<=text.length() )
             {
                 for (int i=0; i<clauseBoundary.length-1; i++) {
                     attrStr.addAttribute(Attribute.INPUT_METHOD_SEGMENT,
diff --git a/jdk/src/windows/classes/sun/awt/windows/WLightweightFramePeer.java b/jdk/src/windows/classes/sun/awt/windows/WLightweightFramePeer.java
index a84aa49..ae2ffcd 100644
--- a/jdk/src/windows/classes/sun/awt/windows/WLightweightFramePeer.java
+++ b/jdk/src/windows/classes/sun/awt/windows/WLightweightFramePeer.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -32,10 +32,11 @@
 import java.awt.event.MouseEvent;
 
 import sun.awt.LightweightFrame;
+import sun.awt.OverrideNativeWindowHandle;
 import sun.swing.JLightweightFrame;
 import sun.swing.SwingAccessor;
 
-public class WLightweightFramePeer extends WFramePeer {
+public class WLightweightFramePeer extends WFramePeer implements OverrideNativeWindowHandle {
 
     public WLightweightFramePeer(LightweightFrame target) {
         super(target);
@@ -50,6 +51,13 @@
         return getLwTarget().getGraphics();
     }
 
+    private native void overrideNativeHandle(long hwnd);
+
+    @Override
+    public void overrideWindowHandle(final long handle) {
+        overrideNativeHandle(handle);
+    }
+
     @Override
     public void show() {
         super.show();
diff --git a/jdk/src/windows/classes/sun/awt/windows/WToolkit.java b/jdk/src/windows/classes/sun/awt/windows/WToolkit.java
index 2171bc3..4792306 100644
--- a/jdk/src/windows/classes/sun/awt/windows/WToolkit.java
+++ b/jdk/src/windows/classes/sun/awt/windows/WToolkit.java
@@ -30,13 +30,19 @@
 import java.awt.im.spi.InputMethodDescriptor;
 import java.awt.image.*;
 import java.awt.peer.*;
+import java.awt.event.FocusEvent;
 import java.awt.event.KeyEvent;
+import java.awt.event.MouseEvent;
 import java.awt.datatransfer.Clipboard;
+import java.awt.TextComponent;
 import java.awt.TrayIcon;
 import java.beans.PropertyChangeListener;
 import java.security.AccessController;
 import java.security.PrivilegedAction;
+import javax.swing.text.JTextComponent;
+
 import sun.awt.AppContext;
+import sun.awt.AWTAccessor;
 import sun.awt.AWTAutoShutdown;
 import sun.awt.LightweightFrame;
 import sun.awt.SunToolkit;
@@ -1101,6 +1107,61 @@
         }
     }
 
+    ///////////////////////////////////////////////////////////////////////////
+    // The following code is used for support of automatic showing of the touch
+    // keyboard for text components and is accessed only from EDT.
+    ///////////////////////////////////////////////////////////////////////////
+    private volatile Component compOnTouchDownEvent;
+    private volatile Component compOnMousePressedEvent;
+
+    @Override
+    public void showOrHideTouchKeyboard(Component comp, AWTEvent e) {
+        if ((comp == null) || (e == null) ||
+            (!(comp instanceof TextComponent) &&
+                !(comp instanceof JTextComponent))) {
+            return;
+        }
+
+        if ((e instanceof MouseEvent) && comp.isEnabled() &&
+            (((comp instanceof TextComponent) &&
+                    ((TextComponent)comp).isEditable()) ||
+                ((comp instanceof JTextComponent) &&
+                    ((JTextComponent)comp).isEditable()))) {
+            MouseEvent me = (MouseEvent)e;
+            if (me.getID() == MouseEvent.MOUSE_PRESSED) {
+                if (AWTAccessor.getMouseEventAccessor()
+                        .isCausedByTouchEvent(me)) {
+                    compOnTouchDownEvent = comp;
+                } else {
+                    compOnMousePressedEvent = comp;
+                }
+            } else if (me.getID() == MouseEvent.MOUSE_RELEASED) {
+                if (AWTAccessor.getMouseEventAccessor()
+                        .isCausedByTouchEvent(me)) {
+                    if (compOnTouchDownEvent == comp) {
+                        showTouchKeyboard(true);
+                    }
+                    compOnTouchDownEvent = null;
+                } else {
+                    if (compOnMousePressedEvent == comp) {
+                        showTouchKeyboard(false);
+                    }
+                    compOnMousePressedEvent = null;
+                }
+            }
+        } else if (e instanceof FocusEvent) {
+            if (e.getID() == FocusEvent.FOCUS_LOST) {
+                hideTouchKeyboard();
+            }
+        }
+    }
+
+    private native void showTouchKeyboard(boolean causedByTouchEvent);
+    private native void hideTouchKeyboard();
+    ///////////////////////////////////////////////////////////////////////////
+    // End of the touch keyboard related code.
+    ///////////////////////////////////////////////////////////////////////////
+
     @Override
     public native boolean syncNativeQueue(final long timeout);
     @Override
diff --git a/jdk/src/windows/lib/tzmappings b/jdk/src/windows/lib/tzmappings
index 0a0b8ad..28917ae 100644
--- a/jdk/src/windows/lib/tzmappings
+++ b/jdk/src/windows/lib/tzmappings
@@ -164,39 +164,63 @@
 GMT Standard Time:88,89::GMT:
 Greenwich:88,89::GMT:
 Greenwich Standard Time:88,89::GMT:
-Argentina Standard Time:900,900::America/Buenos_Aires:
-Azerbaijan Standard Time:901,901:AZ:Asia/Baku:
-Bangladesh Standard Time:902,902::Asia/Dhaka:
-Central Brazilian Standard Time:903,903:BR:America/Cuiaba:
-Central Standard Time (Mexico):904,904::America/Mexico_City:
-Georgian Standard Time:905,905:GE:Asia/Tbilisi:
-Jordan Standard Time:906,906:JO:Asia/Amman:
-Kamchatka Standard Time:907,907:RU:Asia/Kamchatka:
-Mauritius Standard Time:908,908:MU:Indian/Mauritius:
-Middle East Standard Time:909,909:LB:Asia/Beirut:
-Montevideo Standard Time:910,910:UY:America/Montevideo:
-Morocco Standard Time:911,911:MA:Africa/Casablanca:
-Mountain Standard Time (Mexico):912,912:MX:America/Chihuahua:
-Namibia Standard Time:913,913:NA:Africa/Windhoek:
-Pacific Standard Time (Mexico):914,914:MX:America/Tijuana:
-Pakistan Standard Time:915,915::Asia/Karachi:
-Paraguay Standard Time:916,916:PY:America/Asuncion:
-Syria Standard Time:917,917:SY:Asia/Damascus:
-UTC:918,918::UTC:
-UTC+12:919,919::GMT+1200:
-UTC-02:920,920::GMT-0200:
-UTC-11:921,921::GMT-1100:
-Ulaanbaatar Standard Time:922,922::Asia/Ulaanbaatar:
-Venezuela Standard Time:923,923::America/Caracas:
-Magadan Standard Time:924,924::Asia/Magadan:
-Kaliningrad Standard Time:925,925:RU:Europe/Kaliningrad:
-Turkey Standard Time:926,926::Asia/Istanbul:
-Bahia Standard Time:927,927::America/Bahia:
-Libya Standard Time:928,928:LY:Africa/Tripoli:
-Belarus Standard Time:929,929:BY:Europe/Minsk:
-Line Islands Standard Time:930,930::Pacific/Kiritimati:
-Russia Time Zone 10:931,931::Asia/Srednekolymsk:
-Russia Time Zone 11:932,932::Asia/Anadyr:
-Russia Time Zone 3:933,933::Europe/Samara:
-Western Brazilian Standard Time:934,934:BR:America/Rio_Branco:
-Armenian Standard Time:935,935:AM:Asia/Yerevan:
+Aleutian Standard Time:900,900:US:America/Adak:
+Altai Standard Time:901,901::Asia/Barnaul:
+Argentina Standard Time:902,902::America/Buenos_Aires:
+Armenian Standard Time:903,903:AM:Asia/Yerevan:
+Astrakhan Standard Time:904,904::Europe/Astrakhan:
+Aus Central W. Standard Time:905,905::Australia/Eucla:
+Azerbaijan Standard Time:906,906:AZ:Asia/Baku:
+Bahia Standard Time:907,907::America/Bahia:
+Bangladesh Standard Time:908,908::Asia/Dhaka:
+Belarus Standard Time:909,909:BY:Europe/Minsk:
+Bougainville Standard Time:910,910::Pacific/Bougainville:
+Central Brazilian Standard Time:911,911:BR:America/Cuiaba:
+Central Standard Time (Mexico):912,912::America/Mexico_City:
+Chatham Islands Standard Time:913,913::Pacific/Chatham:
+Cuba Standard Time:914,914:CU:America/Havana:
+Easter Island Standard Time:915,915:CL:Pacific/Easter:
+Eastern Standard Time (Mexico):916,916::America/Cancun:
+Georgian Standard Time:917,917:GE:Asia/Tbilisi:
+Haiti Standard Time:918,918:HT:America/Port-au-Prince:
+Jordan Standard Time:919,919:JO:Asia/Amman:
+Kaliningrad Standard Time:920,920:RU:Europe/Kaliningrad:
+Kamchatka Standard Time:921,921:RU:Asia/Kamchatka:
+Libya Standard Time:922,922:LY:Africa/Tripoli:
+Line Islands Standard Time:923,923::Pacific/Kiritimati:
+Lord Howe Standard Time:924,924::Australia/Lord_Howe:
+Magadan Standard Time:925,925::Asia/Magadan:
+Marquesas Standard Time:926,926::Pacific/Marquesas:
+Mauritius Standard Time:927,927:MU:Indian/Mauritius:
+Middle East Standard Time:928,928:LB:Asia/Beirut:
+Montevideo Standard Time:929,929:UY:America/Montevideo:
+Morocco Standard Time:930,930:MA:Africa/Casablanca:
+Mountain Standard Time (Mexico):931,931:MX:America/Chihuahua:
+Namibia Standard Time:932,932:NA:Africa/Windhoek:
+Norfolk Standard Time:933,933::Pacific/Norfolk:
+North Korea Standard Time:934,934:KP:Asia/Pyongyang:
+Pacific Standard Time (Mexico):935,935:MX:America/Tijuana:
+Pakistan Standard Time:936,936::Asia/Karachi:
+Paraguay Standard Time:937,937:PY:America/Asuncion:
+Russia Time Zone 10:938,938::Asia/Srednekolymsk:
+Russia Time Zone 11:939,939::Asia/Anadyr:
+Russia Time Zone 3:940,940::Europe/Samara:
+Saint Pierre Standard Time:941,941:PM:America/Miquelon:
+Sakhalin Standard Time:942,942::Asia/Sakhalin:
+Syria Standard Time:943,943:SY:Asia/Damascus:
+Tocantins Standard Time:944,944::America/Araguaina:
+Tomsk Standard Time:945,945::Asia/Tomsk:
+Transbaikal Standard Time:946,946::Asia/Chita:
+Turkey Standard Time:947,947::Asia/Istanbul:
+Turks And Caicos Standard Time:948,948:TC:America/Grand_Turk:
+UTC+12:949,949::GMT+1200:
+UTC-02:950,950::GMT-0200:
+UTC-08:951,951::GMT-0800:
+UTC-09:952,952::GMT-0900:
+UTC-11:953,953::GMT-1100:
+UTC:954,954::UTC:
+Ulaanbaatar Standard Time:955,955::Asia/Ulaanbaatar:
+Venezuela Standard Time:956,956::America/Caracas:
+W. Mongolia Standard Time:957,957::Asia/Hovd:
+West Bank Standard Time:958,958::Asia/Gaza:
+Western Brazilian Standard Time:959,959:BR:America/Rio_Branco:
diff --git a/jdk/src/windows/native/java/net/NetworkInterface_winXP.c b/jdk/src/windows/native/java/net/NetworkInterface_winXP.c
index 8003abc..d4d8c51 100644
--- a/jdk/src/windows/native/java/net/NetworkInterface_winXP.c
+++ b/jdk/src/windows/native/java/net/NetworkInterface_winXP.c
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -71,7 +71,8 @@
 
 #endif
 
-static int bufsize = 4096;
+const ULONG BUFF_SIZE = 15360;
+const int MAX_TRIES = 3;
 
 /*
  * return an array of IP_ADAPTER_ADDRESSES containing one element
@@ -82,22 +83,26 @@
     DWORD ret, flags;
     IP_ADAPTER_ADDRESSES *adapterInfo;
     ULONG len;
-    adapterInfo = (IP_ADAPTER_ADDRESSES *)malloc (bufsize);
+    int try;
+
+
+    adapterInfo = (IP_ADAPTER_ADDRESSES *) malloc(BUFF_SIZE);
     if (adapterInfo == NULL) {
-        JNU_ThrowByName(env, "java/lang/OutOfMemoryError", "Native heap allocation failure");
+        JNU_ThrowByName(env, "java/lang/OutOfMemoryError",
+            "Native heap allocation failure");
         return -1;
     }
 
-    len = bufsize;
+    len = BUFF_SIZE;
     flags = GAA_FLAG_SKIP_DNS_SERVER;
     flags |= GAA_FLAG_SKIP_MULTICAST;
     flags |= GAA_FLAG_INCLUDE_PREFIX;
     ret = GetAdaptersAddresses(AF_UNSPEC, flags, NULL, adapterInfo, &len);
 
-    if (ret == ERROR_BUFFER_OVERFLOW) {
+    for (try = 0; ret == ERROR_BUFFER_OVERFLOW && try < MAX_TRIES; ++try) {
         IP_ADAPTER_ADDRESSES * newAdapterInfo = NULL;
-        if (len  < (ULONG_MAX - bufsize)) {
-            len = len + bufsize;
+        if (len < (ULONG_MAX - BUFF_SIZE)) {
+            len += BUFF_SIZE;
         }
         newAdapterInfo =
                 (IP_ADAPTER_ADDRESSES *) realloc (adapterInfo, len);
@@ -131,20 +136,22 @@
     DWORD flags, val;
     IP_ADAPTER_ADDRESSES *adapterInfo, *ptr, *ret;
     ULONG len;
-    adapterInfo = (IP_ADAPTER_ADDRESSES *)malloc (bufsize);
+    int try;
+    adapterInfo = (IP_ADAPTER_ADDRESSES *) malloc(BUFF_SIZE);
     if (adapterInfo == NULL) {
-        JNU_ThrowByName(env, "java/lang/OutOfMemoryError", "Native heap allocation failure");
+        JNU_ThrowByName(env, "java/lang/OutOfMemoryError",
+            "Native heap allocation failure");
         return NULL;
     }
-    len = bufsize;
+    len = BUFF_SIZE;
     flags = GAA_FLAG_SKIP_DNS_SERVER;
     flags |= GAA_FLAG_SKIP_MULTICAST;
     flags |= GAA_FLAG_INCLUDE_PREFIX;
     val = GetAdaptersAddresses(AF_UNSPEC, flags, NULL, adapterInfo, &len);
-    if (val == ERROR_BUFFER_OVERFLOW) {
+    for (try = 0; val == ERROR_BUFFER_OVERFLOW && try < MAX_TRIES; ++try) {
         IP_ADAPTER_ADDRESSES * newAdapterInfo = NULL;
-        if (len  < (ULONG_MAX - bufsize)) {
-            len = len + bufsize;
+        if (len < (ULONG_MAX - BUFF_SIZE)) {
+            len += BUFF_SIZE;
         }
         newAdapterInfo =
                 (IP_ADAPTER_ADDRESSES *) realloc (adapterInfo, len);
diff --git a/jdk/src/windows/native/sun/windows/awt.h b/jdk/src/windows/native/sun/windows/awt.h
index e5332df..95b0e1ed 100644
--- a/jdk/src/windows/native/sun/windows/awt.h
+++ b/jdk/src/windows/native/sun/windows/awt.h
@@ -175,6 +175,9 @@
 #define IS_WIN2000 (LOBYTE(LOWORD(::GetVersion())) >= 5)
 #define IS_WINXP ((IS_WIN2000 && HIBYTE(LOWORD(::GetVersion())) >= 1) || LOBYTE(LOWORD(::GetVersion())) > 5)
 #define IS_WINVISTA (LOBYTE(LOWORD(::GetVersion())) >= 6)
+#define IS_WIN8 (                                                              \
+    (IS_WINVISTA && (HIBYTE(LOWORD(::GetVersion())) >= 2)) ||                  \
+    (LOBYTE(LOWORD(::GetVersion())) > 6))
 
 #define IS_WINVER_ATLEAST(maj, min) \
                    ((maj) < LOBYTE(LOWORD(::GetVersion())) || \
diff --git a/jdk/src/windows/native/sun/windows/awt_Component.cpp b/jdk/src/windows/native/sun/windows/awt_Component.cpp
index ed1188e..58993b4 100644
--- a/jdk/src/windows/native/sun/windows/awt_Component.cpp
+++ b/jdk/src/windows/native/sun/windows/awt_Component.cpp
@@ -221,6 +221,10 @@
 AwtComponent::AwtComponent()
 {
     m_mouseButtonClickAllowed = 0;
+    m_touchDownOccurred = FALSE;
+    m_touchUpOccurred = FALSE;
+    m_touchDownPoint.x = m_touchDownPoint.y = 0;
+    m_touchUpPoint.x = m_touchUpPoint.y = 0;
     m_callbacksEnabled = FALSE;
     m_hwnd = NULL;
 
@@ -589,6 +593,11 @@
     /* Subclass the window now so that we can snoop on its messages */
     SubclassHWND();
 
+    AwtToolkit& tk = AwtToolkit::GetInstance();
+    if (tk.IsWin8OrLater() && tk.IsTouchKeyboardAutoShowEnabled()) {
+        tk.TIRegisterTouchWindow(GetHWnd(), TWF_WANTPALM);
+    }
+
     /*
       * Fix for 4046446.
       */
@@ -1709,6 +1718,9 @@
               break;
           }
           break;
+      case WM_TOUCH:
+          WmTouch(wParam, lParam);
+          break;
       case WM_SETCURSOR:
           mr = mrDoDefault;
           if (LOWORD(lParam) == HTCLIENT) {
@@ -2300,6 +2312,38 @@
     return mrDoDefault;
 }
 
+void AwtComponent::WmTouch(WPARAM wParam, LPARAM lParam) {
+    AwtToolkit& tk = AwtToolkit::GetInstance();
+    if (!tk.IsWin8OrLater() || !tk.IsTouchKeyboardAutoShowEnabled()) {
+        return;
+    }
+
+    UINT inputsCount = LOWORD(wParam);
+    TOUCHINPUT* pInputs = new TOUCHINPUT[inputsCount];
+    if (pInputs != NULL) {
+        if (tk.TIGetTouchInputInfo((HTOUCHINPUT)lParam, inputsCount, pInputs,
+                sizeof(TOUCHINPUT)) != 0) {
+            for (UINT i = 0; i < inputsCount; i++) {
+                TOUCHINPUT ti = pInputs[i];
+                if (ti.dwFlags & TOUCHEVENTF_PRIMARY) {
+                    if (ti.dwFlags & TOUCHEVENTF_DOWN) {
+                        m_touchDownPoint.x = ti.x / 100;
+                        m_touchDownPoint.y = ti.y / 100;
+                        ::ScreenToClient(GetHWnd(), &m_touchDownPoint);
+                        m_touchDownOccurred = TRUE;
+                    } else if (ti.dwFlags & TOUCHEVENTF_UP) {
+                        m_touchUpPoint.x = ti.x / 100;
+                        m_touchUpPoint.y = ti.y / 100;
+                        ::ScreenToClient(GetHWnd(), &m_touchUpPoint);
+                        m_touchUpOccurred = TRUE;
+                    }
+                }
+            }
+        }
+        delete[] pInputs;
+    }
+}
+
 /* Double-click variables. */
 static jlong multiClickTime = ::GetDoubleClickTime();
 static int multiClickMaxX = ::GetSystemMetrics(SM_CXDOUBLECLK);
@@ -2342,6 +2386,14 @@
     m_mouseButtonClickAllowed |= GetButtonMK(button);
     lastTime = now;
 
+    BOOL causedByTouchEvent = FALSE;
+    if (m_touchDownOccurred &&
+        (abs(m_touchDownPoint.x - x) <= TOUCH_MOUSE_COORDS_DELTA) &&
+        (abs(m_touchDownPoint.y - y) <= TOUCH_MOUSE_COORDS_DELTA)) {
+        causedByTouchEvent = TRUE;
+        m_touchDownOccurred = FALSE;
+    }
+
     MSG msg;
     InitMessage(&msg, lastMessage, flags, MAKELPARAM(x, y), x, y);
 
@@ -2360,7 +2412,7 @@
 
     SendMouseEvent(java_awt_event_MouseEvent_MOUSE_PRESSED, now, x, y,
                    GetJavaModifiers(), clickCount, JNI_FALSE,
-                   GetButton(button), &msg);
+                   GetButton(button), &msg, causedByTouchEvent);
     /*
      * NOTE: this call is intentionally placed after all other code,
      * since AwtComponent::WmMouseDown() assumes that the cached id of the
@@ -2382,13 +2434,21 @@
 
 MsgRouting AwtComponent::WmMouseUp(UINT flags, int x, int y, int button)
 {
+    BOOL causedByTouchEvent = FALSE;
+    if (m_touchUpOccurred &&
+        (abs(m_touchUpPoint.x - x) <= TOUCH_MOUSE_COORDS_DELTA) &&
+        (abs(m_touchUpPoint.y - y) <= TOUCH_MOUSE_COORDS_DELTA)) {
+        causedByTouchEvent = TRUE;
+        m_touchUpOccurred = FALSE;
+    }
+
     MSG msg;
     InitMessage(&msg, lastMessage, flags, MAKELPARAM(x, y), x, y);
 
     SendMouseEvent(java_awt_event_MouseEvent_MOUSE_RELEASED, TimeHelper::getMessageTimeUTC(),
                    x, y, GetJavaModifiers(), clickCount,
                    (GetButton(button) == java_awt_event_MouseEvent_BUTTON3 ?
-                    TRUE : FALSE), GetButton(button), &msg);
+                    TRUE : FALSE), GetButton(button), &msg, causedByTouchEvent);
     /*
      * If no movement, then report a click following the button release.
      * When WM_MOUSEUP comes to a window without previous WM_MOUSEDOWN,
@@ -3792,25 +3852,36 @@
         if ( m_bitsCandType & bits )
             SetCandidateWindow(iCandType, x - p.x, y - p.y);
     }
-    if (m_bitsCandType != 0) {
-        // REMIND: is there any chance GetProxyFocusOwner() returns NULL here?
-        ::DefWindowProc(ImmGetHWnd(),
-                        WM_IME_NOTIFY, IMN_OPENCANDIDATE, m_bitsCandType);
-    }
 }
 
 void AwtComponent::SetCandidateWindow(int iCandType, int x, int y)
 {
     HWND hwnd = ImmGetHWnd();
     HIMC hIMC = ImmGetContext(hwnd);
-    CANDIDATEFORM cf;
-    cf.dwIndex = iCandType;
-    cf.dwStyle = CFS_POINT;
-    cf.ptCurrentPos.x = x;
-    cf.ptCurrentPos.y = y;
-
-    ImmSetCandidateWindow(hIMC, &cf);
-    ImmReleaseContext(hwnd, hIMC);
+    if (hIMC) {
+        CANDIDATEFORM cf;
+        cf.dwStyle = CFS_POINT;
+        ImmGetCandidateWindow(hIMC, 0, &cf);
+        if (x != cf.ptCurrentPos.x || y != cf.ptCurrentPos.y) {
+            cf.dwIndex = iCandType;
+            cf.dwStyle = CFS_POINT;
+            cf.ptCurrentPos.x = x;
+            cf.ptCurrentPos.y = y;
+            cf.rcArea.left = cf.rcArea.top = cf.rcArea.right = cf.rcArea.bottom = 0;
+            ImmSetCandidateWindow(hIMC, &cf);
+        }
+        COMPOSITIONFORM cfr;
+        cfr.dwStyle = CFS_POINT;
+        ImmGetCompositionWindow(hIMC, &cfr);
+        if (x != cfr.ptCurrentPos.x || y != cfr.ptCurrentPos.y) {
+            cfr.dwStyle = CFS_POINT;
+            cfr.ptCurrentPos.x = x;
+            cfr.ptCurrentPos.y = y;
+            cfr.rcArea.left = cfr.rcArea.top = cfr.rcArea.right = cfr.rcArea.bottom = 0;
+            ImmSetCompositionWindow(hIMC, &cfr);
+        }
+        ImmReleaseContext(hwnd, hIMC);
+    }
 }
 
 MsgRouting AwtComponent::WmImeSetContext(BOOL fSet, LPARAM *lplParam)
@@ -3838,17 +3909,14 @@
 MsgRouting AwtComponent::WmImeNotify(WPARAM subMsg, LPARAM bitsCandType)
 {
     if (!m_useNativeCompWindow) {
-        if (subMsg == IMN_OPENCANDIDATE) {
+        if (subMsg == IMN_OPENCANDIDATE || subMsg == IMN_CHANGECANDIDATE) {
             m_bitsCandType = bitsCandType;
             InquireCandidatePosition();
         } else if (subMsg == IMN_OPENSTATUSWINDOW ||
-                   subMsg == WM_IME_STARTCOMPOSITION) {
-            m_bitsCandType = 0;
-            InquireCandidatePosition();
-        } else if (subMsg == IMN_SETCANDIDATEPOS) {
+                   subMsg == WM_IME_STARTCOMPOSITION ||
+                   subMsg == IMN_SETCANDIDATEPOS) {
             InquireCandidatePosition();
         }
-        return mrConsume;
     }
     return mrDoDefault;
 }
@@ -4909,7 +4977,7 @@
 void AwtComponent::SendMouseEvent(jint id, jlong when, jint x, jint y,
                                   jint modifiers, jint clickCount,
                                   jboolean popupTrigger, jint button,
-                                  MSG *pMsg)
+                                  MSG *pMsg, BOOL causedByTouchEvent)
 {
     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
     CriticalSection::Lock l(GetLock());
@@ -4958,6 +5026,10 @@
 
     DASSERT(mouseEvent != NULL);
     CHECK_NULL(mouseEvent);
+    if (causedByTouchEvent) {
+        env->SetBooleanField(mouseEvent, AwtMouseEvent::causedByTouchEventID,
+            JNI_TRUE);
+    }
     if (pMsg != 0) {
         AwtAWTEvent::saveMSG(env, pMsg, mouseEvent);
     }
diff --git a/jdk/src/windows/native/sun/windows/awt_Component.h b/jdk/src/windows/native/sun/windows/awt_Component.h
index 1084699..99d7afc 100644
--- a/jdk/src/windows/native/sun/windows/awt_Component.h
+++ b/jdk/src/windows/native/sun/windows/awt_Component.h
@@ -67,7 +67,10 @@
 const int ALL_MK_BUTTONS = MK_LBUTTON|MK_MBUTTON|MK_RBUTTON;
 const int X_BUTTONS = MK_XBUTTON1|MK_XBUTTON2;
 
-
+// The allowable difference between coordinates of the WM_TOUCH event and the
+// corresponding WM_LBUTTONDOWN/WM_LBUTTONUP event letting to associate these
+// events, when their coordinates are slightly different.
+const int TOUCH_MOUSE_COORDS_DELTA = 10;
 
 // Whether to check for embedded frame and adjust location
 #define CHECK_EMBEDDED 0
@@ -384,7 +387,7 @@
     void SendMouseEvent(jint id, jlong when, jint x, jint y,
                         jint modifiers, jint clickCount,
                         jboolean popupTrigger, jint button = 0,
-                        MSG *msg = NULL);
+                        MSG *msg = NULL, BOOL causedByTouchEvent = FALSE);
 
     /*
      * Allocate and initialize a new java.awt.event.MouseWheelEvent, and
@@ -526,6 +529,7 @@
     virtual MsgRouting WmNcMouseUp(WPARAM hitTest, int x, int y, int button);
     virtual MsgRouting WmWindowPosChanging(LPARAM windowPos);
     virtual MsgRouting WmWindowPosChanged(LPARAM windowPos);
+    virtual void WmTouch(WPARAM wParam, LPARAM lParam);
 
     // NB: 64-bit: vkey is wParam of the message, but other API's take
     // vkey parameters of type UINT, so we do the cast before dispatching.
@@ -757,6 +761,11 @@
     */
     UINT m_mouseButtonClickAllowed;
 
+    BOOL m_touchDownOccurred;
+    BOOL m_touchUpOccurred;
+    POINT m_touchDownPoint;
+    POINT m_touchUpPoint;
+
     BOOL m_bSubclassed;
     BOOL m_bPauseDestroy;
 
diff --git a/jdk/src/windows/native/sun/windows/awt_Dialog.cpp b/jdk/src/windows/native/sun/windows/awt_Dialog.cpp
index d1c6474..d629f06 100644
--- a/jdk/src/windows/native/sun/windows/awt_Dialog.cpp
+++ b/jdk/src/windows/native/sun/windows/awt_Dialog.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 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
@@ -119,7 +119,8 @@
         if (parent != NULL) {
             JNI_CHECK_PEER_GOTO(parent, done);
             awtParent = (AwtWindow *)pData;
-            hwndParent = awtParent->GetHWnd();
+            HWND oHWnd = awtParent->GetOverriddenHWnd();
+            hwndParent = oHWnd ? oHWnd : awtParent->GetHWnd();
         } else {
             // There is no way to prevent a parentless dialog from showing on
             //  the taskbar other than to specify an invisible parent and set
diff --git a/jdk/src/windows/native/sun/windows/awt_FileDialog.cpp b/jdk/src/windows/native/sun/windows/awt_FileDialog.cpp
index b5d7663..0749cf1 100644
--- a/jdk/src/windows/native/sun/windows/awt_FileDialog.cpp
+++ b/jdk/src/windows/native/sun/windows/awt_FileDialog.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 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
@@ -251,13 +251,7 @@
     OPENFILENAME ofn;
     memset(&ofn, 0, sizeof(ofn));
 
-    /*
-     * There's a situation (see bug 4906972) when InvokeFunction (by which this method is called)
-     * returnes earlier than this method returnes. Probably it's caused due to ReplyMessage system call.
-     * So for the avoidance of this mistiming we need to make new global reference here
-     * (not local as it's used by the hook) and then manage it independently of the calling thread.
-     */
-    peer = env->NewGlobalRef((jobject)p);
+    peer = (jobject)p;
 
     try {
         DASSERT(peer);
diff --git a/jdk/src/windows/native/sun/windows/awt_Frame.cpp b/jdk/src/windows/native/sun/windows/awt_Frame.cpp
index 4982f97..5db33f9 100644
--- a/jdk/src/windows/native/sun/windows/awt_Frame.cpp
+++ b/jdk/src/windows/native/sun/windows/awt_Frame.cpp
@@ -169,7 +169,8 @@
             JNI_CHECK_PEER_GOTO(parent, done);
             {
                 AwtFrame* parent = (AwtFrame *)pData;
-                hwndParent = parent->GetHWnd();
+                HWND oHWnd = parent->GetOverriddenHWnd();
+                hwndParent = oHWnd ? oHWnd : parent->GetHWnd();
             }
         }
 
diff --git a/jdk/src/windows/native/sun/windows/awt_InputTextInfor.cpp b/jdk/src/windows/native/sun/windows/awt_InputTextInfor.cpp
index de9248f..9d996fd 100644
--- a/jdk/src/windows/native/sun/windows/awt_InputTextInfor.cpp
+++ b/jdk/src/windows/native/sun/windows/awt_InputTextInfor.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -202,9 +202,15 @@
          m_lpClauseW == NULL || m_lpReadClauseW == NULL ||
          m_lpClauseW[0] != 0 || m_lpClauseW[m_cClauseW] != (DWORD)m_cStrW ||
          m_lpReadClauseW[0] != 0 || m_lpReadClauseW[m_cReadClauseW] != (DWORD)m_cReadStrW) {
-        lpBndClauseW = NULL;
-        lpReadingClauseW = NULL;
-        return 0;
+        // For cases where IMM sends WM_IME_COMPOSITION with both GCS_COMPSTR and GCS_RESULTSTR
+        // The GCS_RESULTSTR part may have Caluse and Reading information which should not be ignored
+        if (NULL == m_pResultTextInfor) {
+            lpBndClauseW = NULL;
+            lpReadingClauseW = NULL;
+            return 0;
+        } else {
+            return m_pResultTextInfor->GetClauseInfor(lpBndClauseW, lpReadingClauseW);
+        }
     }
 
     int*    bndClauseW = NULL;
@@ -346,10 +352,14 @@
 //
 int AwtInputTextInfor::GetAttributeInfor(int*& lpBndAttrW, BYTE*& lpValAttrW) {
     if (m_cStrW == 0 || m_cAttrW != m_cStrW) {
-        lpBndAttrW = NULL;
-        lpValAttrW = NULL;
+        if (NULL == m_pResultTextInfor) {
+            lpBndAttrW = NULL;
+            lpValAttrW = NULL;
 
-        return 0;
+            return 0;
+        } else {
+            return m_pResultTextInfor->GetAttributeInfor(lpBndAttrW, lpValAttrW);
+        }
     }
 
     int* bndAttrW = NULL;
diff --git a/jdk/src/windows/native/sun/windows/awt_MouseEvent.cpp b/jdk/src/windows/native/sun/windows/awt_MouseEvent.cpp
index 682c6e2..ecc476a 100644
--- a/jdk/src/windows/native/sun/windows/awt_MouseEvent.cpp
+++ b/jdk/src/windows/native/sun/windows/awt_MouseEvent.cpp
@@ -32,6 +32,7 @@
 
 jfieldID AwtMouseEvent::xID;
 jfieldID AwtMouseEvent::yID;
+jfieldID AwtMouseEvent::causedByTouchEventID;
 jfieldID AwtMouseEvent::buttonID;
 
 /************************************************************************
@@ -52,6 +53,11 @@
     DASSERT(AwtMouseEvent::yID != NULL);
     CHECK_NULL(AwtMouseEvent::yID);
 
+    AwtMouseEvent::causedByTouchEventID = env->GetFieldID(
+        cls, "causedByTouchEvent", "Z");
+    DASSERT(AwtMouseEvent::causedByTouchEventID != NULL);
+    CHECK_NULL(AwtMouseEvent::causedByTouchEventID);
+
     AwtMouseEvent::buttonID = env->GetFieldID(cls, "button", "I");
     DASSERT(AwtMouseEvent::buttonID != NULL);
     CHECK_NULL(AwtMouseEvent::buttonID);
diff --git a/jdk/src/windows/native/sun/windows/awt_MouseEvent.h b/jdk/src/windows/native/sun/windows/awt_MouseEvent.h
index f4f3da5..05c2b19 100644
--- a/jdk/src/windows/native/sun/windows/awt_MouseEvent.h
+++ b/jdk/src/windows/native/sun/windows/awt_MouseEvent.h
@@ -39,6 +39,7 @@
     /* java.awt.MouseEvent field ids */
     static jfieldID xID;
     static jfieldID yID;
+    static jfieldID causedByTouchEventID;
     static jfieldID buttonID;
 
 };
diff --git a/jdk/src/windows/native/sun/windows/awt_Toolkit.cpp b/jdk/src/windows/native/sun/windows/awt_Toolkit.cpp
index 4c657ad..2027cab 100644
--- a/jdk/src/windows/native/sun/windows/awt_Toolkit.cpp
+++ b/jdk/src/windows/native/sun/windows/awt_Toolkit.cpp
@@ -29,6 +29,8 @@
 #include <signal.h>
 #include <windowsx.h>
 #include <process.h>
+#include <shellapi.h>
+#include <shlwapi.h>
 
 #include "awt_DrawingSurface.h"
 #include "awt_AWTEvent.h"
@@ -292,6 +294,13 @@
     m_isDynamicLayoutSet = FALSE;
     m_areExtraMouseButtonsEnabled = TRUE;
 
+    m_isWin8OrLater = FALSE;
+    m_touchKbrdAutoShowIsEnabled = FALSE;
+    m_touchKbrdExeFilePath = NULL;
+    m_pRegisterTouchWindow = NULL;
+    m_pGetTouchInputInfo = NULL;
+    m_pCloseTouchInputHandle = NULL;
+
     m_verifyComponents = FALSE;
     m_breakOnError = FALSE;
 
@@ -345,6 +354,149 @@
     return hwnd;
 }
 
+void AwtToolkit::InitTouchKeyboardExeFilePath() {
+    enum RegistryView { WOW64_32BIT, WOW64_64BIT };
+    const TCHAR tabTipCoKeyName[] = _T("SOFTWARE\\Classes\\CLSID\\")
+        _T("{054AAE20-4BEA-4347-8A35-64A533254A9D}\\LocalServer32");
+    HKEY hTabTipCoKey = NULL;
+    RegistryView regViewWithTabTipCoKey = WOW64_32BIT;
+
+    if (::RegOpenKeyEx(HKEY_LOCAL_MACHINE, tabTipCoKeyName, 0,
+            KEY_READ | KEY_WOW64_32KEY, &hTabTipCoKey) != ERROR_SUCCESS) {
+        if (::RegOpenKeyEx(HKEY_LOCAL_MACHINE, tabTipCoKeyName, 0,
+                KEY_READ | KEY_WOW64_64KEY, &hTabTipCoKey) != ERROR_SUCCESS) {
+            return;
+        } else {
+            regViewWithTabTipCoKey = WOW64_64BIT;
+        }
+    }
+
+    DWORD keyValType = 0;
+    DWORD bytesCopied = 0;
+    if ((::RegQueryValueEx(hTabTipCoKey, NULL, NULL, &keyValType, NULL,
+            &bytesCopied) != ERROR_SUCCESS) ||
+        ((keyValType != REG_EXPAND_SZ) && (keyValType != REG_SZ))) {
+        if (hTabTipCoKey != NULL) {
+            ::RegCloseKey(hTabTipCoKey);
+        }
+        return;
+    }
+
+    // Increase the buffer size for 1 additional null-terminating character.
+    bytesCopied += sizeof(TCHAR);
+    TCHAR* tabTipFilePath = new TCHAR[bytesCopied / sizeof(TCHAR)];
+    ::memset(tabTipFilePath, 0, bytesCopied);
+
+    DWORD oldBytesCopied = bytesCopied;
+    if (::RegQueryValueEx(hTabTipCoKey, NULL, NULL, NULL,
+            (LPBYTE)tabTipFilePath, &bytesCopied) == ERROR_SUCCESS) {
+        const TCHAR searchedStr[] = _T("%CommonProgramFiles%");
+        const size_t searchedStrLen = ::_tcslen(searchedStr);
+        int searchedStrStartIndex = -1;
+
+        TCHAR* commonFilesDirPath = NULL;
+        DWORD commonFilesDirPathLen = 0;
+
+        // Check, if '%CommonProgramFiles%' string is present in the defined
+        // path of the touch keyboard executable.
+        TCHAR* const searchedStrStart = ::_tcsstr(tabTipFilePath, searchedStr);
+        if (searchedStrStart != NULL) {
+            searchedStrStartIndex = searchedStrStart - tabTipFilePath;
+
+            // Get value of 'CommonProgramFiles' environment variable, if the
+            // file path of the touch keyboard executable was found in 32-bit
+            // registry view, otherwise get value of 'CommonProgramW6432'.
+            const TCHAR envVar32BitName[] = _T("CommonProgramFiles");
+            const TCHAR envVar64BitName[] = _T("CommonProgramW6432");
+            const TCHAR* envVarName = (regViewWithTabTipCoKey == WOW64_32BIT ?
+                envVar32BitName : envVar64BitName);
+
+            DWORD charsStored = ::GetEnvironmentVariable(envVarName, NULL, 0);
+            if (charsStored > 0) {
+                commonFilesDirPath = new TCHAR[charsStored];
+                ::memset(commonFilesDirPath, 0, charsStored * sizeof(TCHAR));
+
+                DWORD oldCharsStored = charsStored;
+                if (((charsStored = ::GetEnvironmentVariable(envVarName,
+                        commonFilesDirPath, charsStored)) > 0) &&
+                    (charsStored <= oldCharsStored)) {
+                    commonFilesDirPathLen = charsStored;
+                } else {
+                    delete[] commonFilesDirPath;
+                    commonFilesDirPath = NULL;
+                }
+            }
+        }
+
+        // Calculate 'm_touchKbrdExeFilePath' length in characters including
+        // the null-terminating character.
+        DWORD exeFilePathLen = oldBytesCopied / sizeof(TCHAR);
+        if (commonFilesDirPathLen > 0) {
+            exeFilePathLen = exeFilePathLen - searchedStrLen +
+                commonFilesDirPathLen;
+        }
+
+        if (m_touchKbrdExeFilePath != NULL) {
+            delete[] m_touchKbrdExeFilePath;
+            m_touchKbrdExeFilePath = NULL;
+        }
+        m_touchKbrdExeFilePath = new TCHAR[exeFilePathLen];
+        ::memset(m_touchKbrdExeFilePath, 0, exeFilePathLen * sizeof(TCHAR));
+
+        if (commonFilesDirPathLen > 0) {
+            ::_tcsncpy_s(m_touchKbrdExeFilePath, exeFilePathLen, tabTipFilePath,
+                searchedStrStartIndex);
+            DWORD charsCopied = searchedStrStartIndex;
+
+            ::_tcsncpy_s(m_touchKbrdExeFilePath + charsCopied,
+                exeFilePathLen - charsCopied, commonFilesDirPath,
+                commonFilesDirPathLen);
+            charsCopied += commonFilesDirPathLen;
+
+            ::_tcsncpy_s(m_touchKbrdExeFilePath + charsCopied,
+                exeFilePathLen - charsCopied, searchedStrStart + searchedStrLen,
+                bytesCopied / sizeof(TCHAR) -
+                    (searchedStrStartIndex + searchedStrLen));
+        } else {
+            ::_tcsncpy_s(m_touchKbrdExeFilePath, exeFilePathLen, tabTipFilePath,
+                bytesCopied / sizeof(TCHAR));
+        }
+
+        // Remove leading and trailing quotation marks.
+        ::StrTrim(m_touchKbrdExeFilePath, _T("\""));
+
+        // Verify that a file with the path 'm_touchKbrdExeFilePath' exists.
+        DWORD fileAttrs = ::GetFileAttributes(m_touchKbrdExeFilePath);
+        DWORD err = ::GetLastError();
+        if ((fileAttrs == INVALID_FILE_ATTRIBUTES) ||
+            (fileAttrs & FILE_ATTRIBUTE_DIRECTORY)) {
+            delete[] m_touchKbrdExeFilePath;
+            m_touchKbrdExeFilePath = NULL;
+        }
+
+        if (commonFilesDirPath != NULL) {
+            delete[] commonFilesDirPath;
+        }
+    }
+
+    if (tabTipFilePath != NULL) {
+        delete[] tabTipFilePath;
+    }
+    if (hTabTipCoKey != NULL) {
+        ::RegCloseKey(hTabTipCoKey);
+    }
+}
+
+HWND AwtToolkit::GetTouchKeyboardWindow() {
+    const TCHAR wndClassName[] = _T("IPTip_Main_Window");
+    HWND hwnd = ::FindWindow(wndClassName, NULL);
+    if ((hwnd != NULL) && ::IsWindow(hwnd) && ::IsWindowEnabled(hwnd) &&
+        ::IsWindowVisible(hwnd)) {
+        return hwnd;
+    }
+    return NULL;
+}
+
 
 struct ToolkitThreadProc_Data {
     bool result;
@@ -503,6 +655,52 @@
 
     awt_dnd_initialize();
 
+    /*
+     * Initialization of the touch keyboard related variables.
+     */
+    tk.m_isWin8OrLater = IS_WIN8;
+
+    TRY;
+
+    JNIEnv* env = AwtToolkit::GetEnv();
+    jclass sunToolkitCls = env->FindClass("sun/awt/SunToolkit");
+    DASSERT(sunToolkitCls != 0);
+    CHECK_NULL_RETURN(sunToolkitCls, FALSE);
+
+    jmethodID isTouchKeyboardAutoShowEnabledMID = env->GetStaticMethodID(
+        sunToolkitCls, "isTouchKeyboardAutoShowEnabled", "()Z");
+    DASSERT(isTouchKeyboardAutoShowEnabledMID != 0);
+    CHECK_NULL_RETURN(isTouchKeyboardAutoShowEnabledMID, FALSE);
+
+    tk.m_touchKbrdAutoShowIsEnabled = env->CallStaticBooleanMethod(
+        sunToolkitCls, isTouchKeyboardAutoShowEnabledMID);
+
+    CATCH_BAD_ALLOC_RET(FALSE);
+
+    if (tk.m_isWin8OrLater && tk.m_touchKbrdAutoShowIsEnabled) {
+        tk.InitTouchKeyboardExeFilePath();
+        HMODULE hUser32Dll = ::LoadLibrary(_T("user32.dll"));
+        if (hUser32Dll != NULL) {
+            tk.m_pRegisterTouchWindow = (RegisterTouchWindowFunc)
+                ::GetProcAddress(hUser32Dll, "RegisterTouchWindow");
+            tk.m_pGetTouchInputInfo = (GetTouchInputInfoFunc)
+                ::GetProcAddress(hUser32Dll, "GetTouchInputInfo");
+            tk.m_pCloseTouchInputHandle = (CloseTouchInputHandleFunc)
+                ::GetProcAddress(hUser32Dll, "CloseTouchInputHandle");
+        }
+
+        if ((tk.m_pRegisterTouchWindow == NULL) ||
+            (tk.m_pGetTouchInputInfo == NULL) ||
+            (tk.m_pCloseTouchInputHandle == NULL)) {
+            tk.m_pRegisterTouchWindow = NULL;
+            tk.m_pGetTouchInputInfo = NULL;
+            tk.m_pCloseTouchInputHandle = NULL;
+        }
+    }
+    /*
+     * End of the touch keyboard related initialization code.
+     */
+
     return TRUE;
 }
 
@@ -527,6 +725,14 @@
     awt_dnd_uninitialize();
     awt_clipboard_uninitialize((JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2));
 
+    if (tk.m_touchKbrdExeFilePath != NULL) {
+        delete[] tk.m_touchKbrdExeFilePath;
+        tk.m_touchKbrdExeFilePath = NULL;
+    }
+    tk.m_pRegisterTouchWindow = NULL;
+    tk.m_pGetTouchInputInfo = NULL;
+    tk.m_pCloseTouchInputHandle = NULL;
+
     if (tk.m_inputMethodHWnd != NULL) {
         ::SendMessage(tk.m_inputMethodHWnd, WM_IME_CONTROL, IMC_OPENSTATUSWINDOW, 0);
     }
@@ -2663,6 +2869,32 @@
     CATCH_BAD_ALLOC_RET(NULL);
 }
 
+JNIEXPORT void JNICALL
+Java_sun_awt_windows_WToolkit_showTouchKeyboard(JNIEnv *env, jobject self,
+    jboolean causedByTouchEvent)
+{
+    AwtToolkit& tk = AwtToolkit::GetInstance();
+    if (!tk.IsWin8OrLater() || !tk.IsTouchKeyboardAutoShowEnabled()) {
+        return;
+    }
+
+    if (causedByTouchEvent ||
+        (tk.IsTouchKeyboardAutoShowSystemEnabled() &&
+            !tk.IsAnyKeyboardAttached())) {
+        tk.ShowTouchKeyboard();
+    }
+}
+
+JNIEXPORT void JNICALL
+Java_sun_awt_windows_WToolkit_hideTouchKeyboard(JNIEnv *env, jobject self)
+{
+    AwtToolkit& tk = AwtToolkit::GetInstance();
+    if (!tk.IsWin8OrLater() || !tk.IsTouchKeyboardAutoShowEnabled()) {
+        return;
+    }
+    tk.HideTouchKeyboard();
+}
+
 JNIEXPORT jboolean JNICALL
 Java_sun_awt_windows_WToolkit_syncNativeQueue(JNIEnv *env, jobject self, jlong timeout)
 {
@@ -2735,3 +2967,119 @@
 UINT AwtToolkit::GetNumberOfButtons() {
     return MOUSE_BUTTONS_WINDOWS_SUPPORTED;
 }
+
+bool AwtToolkit::IsWin8OrLater() {
+    return m_isWin8OrLater;
+}
+
+bool AwtToolkit::IsTouchKeyboardAutoShowEnabled() {
+    return m_touchKbrdAutoShowIsEnabled;
+}
+
+bool AwtToolkit::IsAnyKeyboardAttached() {
+    UINT numDevs = 0;
+    UINT numDevsRet = 0;
+    const UINT devListTypeSize = sizeof(RAWINPUTDEVICELIST);
+    if ((::GetRawInputDeviceList(NULL, &numDevs, devListTypeSize) != 0) ||
+        (numDevs == 0)) {
+        return false;
+    }
+
+    RAWINPUTDEVICELIST* pDevList = new RAWINPUTDEVICELIST[numDevs];
+    while (((numDevsRet = ::GetRawInputDeviceList(pDevList, &numDevs,
+            devListTypeSize)) == (UINT)-1) &&
+        (::GetLastError() == ERROR_INSUFFICIENT_BUFFER)) {
+        if (pDevList != NULL) {
+            delete[] pDevList;
+        }
+        pDevList = new RAWINPUTDEVICELIST[numDevs];
+    }
+
+    bool keyboardIsAttached = false;
+    if (numDevsRet != (UINT)-1) {
+        for (UINT i = 0; i < numDevsRet; i++) {
+            if (pDevList[i].dwType == RIM_TYPEKEYBOARD) {
+                keyboardIsAttached = true;
+                break;
+            }
+        }
+    }
+
+    if (pDevList != NULL) {
+        delete[] pDevList;
+    }
+    return keyboardIsAttached;
+}
+
+bool AwtToolkit::IsTouchKeyboardAutoShowSystemEnabled() {
+    const TCHAR tabTipKeyName[] = _T("SOFTWARE\\Microsoft\\TabletTip\\1.7");
+    HKEY hTabTipKey = NULL;
+    if (::RegOpenKeyEx(HKEY_CURRENT_USER, tabTipKeyName, 0, KEY_READ,
+            &hTabTipKey) != ERROR_SUCCESS) {
+        return false;
+    }
+
+    const TCHAR enableAutoInvokeValName[] = _T("EnableDesktopModeAutoInvoke");
+    DWORD keyValType = 0;
+    bool autoShowIsEnabled = false;
+    if (::RegQueryValueEx(hTabTipKey, enableAutoInvokeValName, NULL,
+            &keyValType, NULL, NULL) == ERROR_SUCCESS) {
+        if (keyValType == REG_DWORD) {
+            DWORD enableAutoInvokeVal = 0;
+            DWORD bytesCopied = sizeof(DWORD);
+            if (::RegQueryValueEx(hTabTipKey, enableAutoInvokeValName, NULL,
+                    NULL, (LPBYTE)(DWORD*)&enableAutoInvokeVal,
+                    &bytesCopied) == ERROR_SUCCESS) {
+                autoShowIsEnabled = (enableAutoInvokeVal == 0 ? false : true);
+            }
+        }
+    }
+
+    if (hTabTipKey != NULL) {
+        ::RegCloseKey(hTabTipKey);
+    }
+    return autoShowIsEnabled;
+}
+
+void AwtToolkit::ShowTouchKeyboard() {
+    if (m_isWin8OrLater && m_touchKbrdAutoShowIsEnabled &&
+        (m_touchKbrdExeFilePath != NULL)) {
+        HINSTANCE retVal = ::ShellExecute(NULL, _T("open"),
+            m_touchKbrdExeFilePath, NULL, NULL, SW_SHOW);
+        if ((int)retVal <= 32) {
+            DTRACE_PRINTLN1("AwtToolkit::ShowTouchKeyboard: Failed"
+                ", retVal='%d'", (int)retVal);
+        }
+    }
+}
+
+void AwtToolkit::HideTouchKeyboard() {
+    if (m_isWin8OrLater && m_touchKbrdAutoShowIsEnabled) {
+        HWND hwnd = GetTouchKeyboardWindow();
+        if (hwnd != NULL) {
+            ::PostMessage(hwnd, WM_SYSCOMMAND, SC_CLOSE, 0);
+        }
+    }
+}
+
+BOOL AwtToolkit::TIRegisterTouchWindow(HWND hWnd, ULONG ulFlags) {
+    if (m_pRegisterTouchWindow == NULL) {
+        return FALSE;
+    }
+    return m_pRegisterTouchWindow(hWnd, ulFlags);
+}
+
+BOOL AwtToolkit::TIGetTouchInputInfo(HTOUCHINPUT hTouchInput,
+    UINT cInputs, PTOUCHINPUT pInputs, int cbSize) {
+    if (m_pGetTouchInputInfo == NULL) {
+        return FALSE;
+    }
+    return m_pGetTouchInputInfo(hTouchInput, cInputs, pInputs, cbSize);
+}
+
+BOOL AwtToolkit::TICloseTouchInputHandle(HTOUCHINPUT hTouchInput) {
+    if (m_pCloseTouchInputHandle == NULL) {
+        return FALSE;
+    }
+    return m_pCloseTouchInputHandle(hTouchInput);
+}
diff --git a/jdk/src/windows/native/sun/windows/awt_Toolkit.h b/jdk/src/windows/native/sun/windows/awt_Toolkit.h
index e0de73d..0c014c9 100644
--- a/jdk/src/windows/native/sun/windows/awt_Toolkit.h
+++ b/jdk/src/windows/native/sun/windows/awt_Toolkit.h
@@ -158,6 +158,48 @@
                 GetCurrentThreadId(), &(cs), THIS_FILE, __LINE__); \
 }
 
+// Redefine WinAPI values related to touch input, if OS < Windows 7.
+#if (!defined(WINVER) || ((WINVER) < 0x0601))
+    /*
+     * RegisterTouchWindow flag values
+     */
+    #define TWF_FINETOUCH       (0x00000001)
+    #define TWF_WANTPALM        (0x00000002)
+
+    #define WM_TOUCH                        0x0240
+
+    /*
+     * Touch input handle
+     */
+    typedef HANDLE HTOUCHINPUT;
+
+    typedef struct tagTOUCHINPUT {
+        LONG x;
+        LONG y;
+        HANDLE hSource;
+        DWORD dwID;
+        DWORD dwFlags;
+        DWORD dwMask;
+        DWORD dwTime;
+        ULONG_PTR dwExtraInfo;
+        DWORD cxContact;
+        DWORD cyContact;
+    } TOUCHINPUT, *PTOUCHINPUT;
+    typedef TOUCHINPUT const * PCTOUCHINPUT;
+
+    /*
+     * Touch input flag values (TOUCHINPUT.dwFlags)
+     */
+    #define TOUCHEVENTF_MOVE            0x0001
+    #define TOUCHEVENTF_DOWN            0x0002
+    #define TOUCHEVENTF_UP              0x0004
+    #define TOUCHEVENTF_INRANGE         0x0008
+    #define TOUCHEVENTF_PRIMARY         0x0010
+    #define TOUCHEVENTF_NOCOALESCE      0x0020
+    #define TOUCHEVENTF_PEN             0x0040
+    #define TOUCHEVENTF_PALM            0x0080
+#endif
+
 /************************************************************************
  * AwtToolkit class
  */
@@ -193,6 +235,17 @@
     void setExtraMouseButtonsEnabled(BOOL enable);
     static UINT GetNumberOfButtons();
 
+    bool IsWin8OrLater();
+    bool IsTouchKeyboardAutoShowEnabled();
+    bool IsAnyKeyboardAttached();
+    bool IsTouchKeyboardAutoShowSystemEnabled();
+    void ShowTouchKeyboard();
+    void HideTouchKeyboard();
+    BOOL TIRegisterTouchWindow(HWND hWnd, ULONG ulFlags);
+    BOOL TIGetTouchInputInfo(HTOUCHINPUT hTouchInput,
+        UINT cInputs, PTOUCHINPUT pInputs, int cbSize);
+    BOOL TICloseTouchInputHandle(HTOUCHINPUT hTouchInput);
+
     INLINE BOOL localPump() { return m_localPump; }
     INLINE BOOL VerifyComponents() { return FALSE; } // TODO: Use new DebugHelper class to set this flag
     INLINE HWND GetHWnd() { return m_toolkitHWnd; }
@@ -391,6 +444,9 @@
 private:
     HWND CreateToolkitWnd(LPCTSTR name);
 
+    void InitTouchKeyboardExeFilePath();
+    HWND GetTouchKeyboardWindow();
+
     BOOL m_localPump;
     DWORD m_mainThreadId;
     HWND m_toolkitHWnd;
@@ -400,6 +456,18 @@
     BOOL m_isDisposed; // set to TRUE at end of Dispose
     BOOL m_areExtraMouseButtonsEnabled;
 
+    typedef BOOL (WINAPI *RegisterTouchWindowFunc)(HWND hWnd, ULONG ulFlags);
+    typedef BOOL (WINAPI *GetTouchInputInfoFunc)(HTOUCHINPUT hTouchInput,
+        UINT cInputs, PTOUCHINPUT pInputs, int cbSize);
+    typedef BOOL (WINAPI *CloseTouchInputHandleFunc)(HTOUCHINPUT hTouchInput);
+
+    BOOL m_isWin8OrLater;
+    BOOL m_touchKbrdAutoShowIsEnabled;
+    TCHAR* m_touchKbrdExeFilePath;
+    RegisterTouchWindowFunc m_pRegisterTouchWindow;
+    GetTouchInputInfoFunc m_pGetTouchInputInfo;
+    CloseTouchInputHandleFunc m_pCloseTouchInputHandle;
+
     BOOL m_vmSignalled; // set to TRUE if QUERYENDSESSION has successfully
                         // raised SIGTERM
 
diff --git a/jdk/src/windows/native/sun/windows/awt_Window.cpp b/jdk/src/windows/native/sun/windows/awt_Window.cpp
index 7bbefc4..5f848aa 100644
--- a/jdk/src/windows/native/sun/windows/awt_Window.cpp
+++ b/jdk/src/windows/native/sun/windows/awt_Window.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 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
@@ -148,6 +148,10 @@
     jboolean isFSEMState;
 };
 
+struct OverrideHandle {
+    jobject frame;
+    HWND handle;
+};
 
 /************************************************************************
  * AwtWindow fields
@@ -223,6 +227,7 @@
     m_alwaysOnTop = false;
 
     fullScreenExclusiveModeState = FALSE;
+    m_overriddenHwnd = NULL;
 }
 
 AwtWindow::~AwtWindow()
@@ -2471,6 +2476,24 @@
    delete rfs;
 }
 
+void AwtWindow::_OverrideHandle(void *param)
+{
+    JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
+
+    OverrideHandle* oh = (OverrideHandle *)param;
+    jobject self = oh->frame;
+    AwtWindow *f = NULL;
+
+    PDATA pData;
+    JNI_CHECK_PEER_GOTO(self, ret);
+    f = (AwtWindow *)pData;
+    f->OverrideHWnd(oh->handle);
+ret:
+    env->DeleteGlobalRef(self);
+
+    delete oh;
+}
+
 /*
  * This is AwtWindow-specific function that is not intended for reusing
  */
@@ -3108,7 +3131,29 @@
     CATCH_BAD_ALLOC;
 }
 
-} /* extern "C" */
+/*
+
+* Class:     sun_awt_windows_WLightweightFramePeer
+* Method:    overrideNativeHandle
+* Signature: (J)V
+*/
+
+JNIEXPORT void JNICALL Java_sun_awt_windows_WLightweightFramePeer_overrideNativeHandle
+(JNIEnv *env, jobject self, jlong hwnd)
+{
+    TRY;
+
+    OverrideHandle *oh = new OverrideHandle;
+    oh->frame = env->NewGlobalRef(self);
+    oh->handle = (HWND)hwnd;
+
+    AwtToolkit::GetInstance().SyncCall(AwtFrame::_OverrideHandle, oh);
+    // global ref and oh are deleted in _OverrideHandle()
+
+    CATCH_BAD_ALLOC;
+}
+
+}/* extern "C" */
 
 
 /************************************************************************
diff --git a/jdk/src/windows/native/sun/windows/awt_Window.h b/jdk/src/windows/native/sun/windows/awt_Window.h
index 1a92a67..1185355 100644
--- a/jdk/src/windows/native/sun/windows/awt_Window.h
+++ b/jdk/src/windows/native/sun/windows/awt_Window.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -241,6 +241,7 @@
     static void _UpdateWindow(void* param);
     static void _RepositionSecurityWarning(void* param);
     static void _SetFullScreenExclusiveModeState(void* param);
+    static void _OverrideHandle(void *param);
 
     inline static BOOL IsResizing() {
         return sm_resizing;
@@ -256,6 +257,9 @@
 
     static void FocusedWindowChanged(HWND from, HWND to);
 
+    inline HWND GetOverriddenHWnd() { return m_overriddenHwnd; }
+    inline void OverrideHWnd(HWND hwnd) { m_overriddenHwnd = hwnd; }
+
 private:
     static int ms_instanceCounter;
     static HHOOK ms_hCBTFilter;
@@ -307,6 +311,9 @@
     // The tooltip that appears when hovering the icon
     HWND securityTooltipWindow;
 
+    //Allows substitute parent window with JavaFX stage to make it below a dialog
+    HWND m_overriddenHwnd;
+
     UINT warningWindowWidth;
     UINT warningWindowHeight;
     void InitSecurityWarningSize(JNIEnv *env);
diff --git a/jdk/test/java/awt/FileDialog/FileDialogMemoryLeak/FileDialogLeakTest.java b/jdk/test/java/awt/FileDialog/FileDialogMemoryLeak/FileDialogLeakTest.java
new file mode 100644
index 0000000..4f946b8
--- /dev/null
+++ b/jdk/test/java/awt/FileDialog/FileDialogMemoryLeak/FileDialogLeakTest.java
@@ -0,0 +1,72 @@
+/*
+ * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.awt.*;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * @test
+ * @bug 8177758
+ * @requires os.family == "windows"
+ * @summary Regression in java.awt.FileDialog
+ * @run main FileDialogLeakTest
+ */
+
+public class FileDialogLeakTest {
+    static CountDownLatch latch = new CountDownLatch(3);
+    static boolean passed;
+
+    public static void main(String[] args) throws Exception {
+        test();
+        System.gc();
+        System.runFinalization();
+        latch.await(1, TimeUnit.SECONDS);
+        if (!passed) {
+            throw new RuntimeException("Test failed.");
+        }
+    }
+
+    private static void test() throws Exception {
+        FileDialog fd = new FileDialog((Frame) null) {
+            @Override
+            protected void finalize() throws Throwable {
+                System.out.println("Finalize");
+                super.finalize();
+                passed = true;
+                latch.countDown();
+            }
+        };
+
+        new Thread(() -> {
+            latch.countDown();
+            fd.setVisible(true);
+            latch.countDown();
+        }).start();
+        latch.await(1, TimeUnit.SECONDS);
+        fd.dispose();
+        latch.await(1, TimeUnit.SECONDS);
+    }
+
+}
+
diff --git a/jdk/test/java/awt/image/DrawImage/IncorrectClipXorModeSurface2Surface.java b/jdk/test/java/awt/image/DrawImage/IncorrectClipXorModeSurface2Surface.java
index 8a9b1bd..c23a1cf 100644
--- a/jdk/test/java/awt/image/DrawImage/IncorrectClipXorModeSurface2Surface.java
+++ b/jdk/test/java/awt/image/DrawImage/IncorrectClipXorModeSurface2Surface.java
@@ -40,7 +40,7 @@
 
 /**
  * @test
- * @bug 8061831
+ * @bug 8061831 8130400
  * @summary Tests drawing volatile image to volatile image using different
  *          clips + xor mode. Results of the blit compatibleImage to
  *          compatibleImage is used for comparison.
diff --git a/jdk/test/java/lang/Runtime/shutdown/ShutdownInterruptedMain.java b/jdk/test/java/lang/Runtime/shutdown/ShutdownInterruptedMain.java
new file mode 100644
index 0000000..080ca56
--- /dev/null
+++ b/jdk/test/java/lang/Runtime/shutdown/ShutdownInterruptedMain.java
@@ -0,0 +1,63 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8154017
+ * @library /lib/testlibrary
+ * @build jdk.testlibrary.*
+ * @summary Shutdown hooks are racing against shutdown sequence,
+            if System.exit()-calling thread is interrupted
+ * @run main ShutdownInterruptedMain exec
+ */
+
+import jdk.testlibrary.OutputAnalyzer;
+import static jdk.testlibrary.ProcessTools.createJavaProcessBuilder;
+import static jdk.testlibrary.ProcessTools.executeProcess;
+
+public class ShutdownInterruptedMain {
+
+    public static void main(String[] args) throws Throwable {
+        if (args.length > 0) {
+            ProcessBuilder pb = createJavaProcessBuilder(true, "ShutdownInterruptedMain");
+            OutputAnalyzer output = executeProcess(pb);
+            output.shouldContain("Shutdown Hook");
+            output.shouldHaveExitValue(0);
+            return;
+        }
+
+        Runtime.getRuntime().addShutdownHook(new Thread() {
+            @Override
+            public void run() {
+                // Wait for the race to unfold:
+                try {
+                    Thread.sleep(5_000);
+                } catch (InterruptedException e) {}
+                System.out.println("Shutdown Hook");
+                System.out.flush();
+            }
+        });
+        Thread.currentThread().interrupt();
+        System.exit(0);
+    }
+}
diff --git a/jdk/test/java/lang/ref/FinalizerHistogramTest.java b/jdk/test/java/lang/ref/FinalizerHistogramTest.java
new file mode 100644
index 0000000..cb57093
--- /dev/null
+++ b/jdk/test/java/lang/ref/FinalizerHistogramTest.java
@@ -0,0 +1,104 @@
+/*
+ * Copyright (c) 2015, 2017, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.Condition;
+import java.util.concurrent.locks.ReentrantLock;
+
+import java.lang.reflect.Method;
+import java.lang.reflect.Field;
+
+/*
+ * @test
+ * @summary Unit test for FinalizerHistogram
+ * @run main FinalizerHistogramTest
+ */
+
+public class FinalizerHistogramTest {
+    static ReentrantLock lock = new ReentrantLock();
+    static volatile int wasInitialized = 0;
+    static volatile int wasTrapped = 0;
+    static final int objectsCount = 1000;
+
+    static class MyObject {
+        public MyObject() {
+            // Make sure object allocation/deallocation is not optimized out
+            wasInitialized += 1;
+        }
+
+        protected void finalize() {
+            // Trap the object in a finalization queue
+            wasTrapped += 1;
+            lock.lock();
+        }
+    }
+
+    public static void main(String[] argvs) {
+        try {
+            lock.lock();
+            for(int i = 0; i < objectsCount; ++i) {
+                new MyObject();
+            }
+            System.out.println("Objects intialized: " + objectsCount);
+            System.gc();
+            while(wasTrapped < 1);
+
+            Class<?> klass = Class.forName("java.lang.ref.FinalizerHistogram");
+
+            Method m = klass.getDeclaredMethod("getFinalizerHistogram");
+            m.setAccessible(true);
+            Object entries[] = (Object[]) m.invoke(null);
+
+            Class<?> entryKlass = Class.forName("java.lang.ref.FinalizerHistogram$Entry");
+            Field name = entryKlass.getDeclaredField("className");
+            name.setAccessible(true);
+            Field count = entryKlass.getDeclaredField("instanceCount");
+            count.setAccessible(true);
+
+            System.out.println("Unreachable instances waiting for finalization");
+            System.out.println("#instances  class name");
+            System.out.println("-----------------------");
+
+            boolean found = false;
+            for (Object entry : entries) {
+                Object e = entryKlass.cast(entry);
+                System.out.printf("%10d %s\n", count.get(e), name.get(e));
+                if (((String) name.get(e)).indexOf("MyObject") != -1 ) {
+                    found = true;
+                }
+            }
+
+            if (!found) {
+                throw new RuntimeException("MyObject is not found in test output");
+            }
+
+            System.out.println("Test PASSED");
+        } catch(Exception e) {
+           System.err.println("Test failed with " + e);
+           e.printStackTrace(System.err);
+           throw new RuntimeException("Test failed");
+        } finally {
+            lock.unlock();
+        }
+    }
+}
diff --git a/jdk/test/java/text/Format/DecimalFormat/Bug8165466.java b/jdk/test/java/text/Format/DecimalFormat/Bug8165466.java
new file mode 100644
index 0000000..83873da
--- /dev/null
+++ b/jdk/test/java/text/Format/DecimalFormat/Bug8165466.java
@@ -0,0 +1,95 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+/*
+ * @test
+ * @bug 8165466
+ * @summary Checks the subsequent function calls of the DecimalFormat.format()
+ *          method in which the minimumFractionDigit is set to 0 and one of
+ *          the format() call include formatting of the number with zero
+ *          fraction value e.g. 0.00, 9.00
+ */
+
+import java.text.DecimalFormat;
+import java.util.Locale;
+
+public class Bug8165466 {
+
+    public static void main(String[] args) {
+        DecimalFormat nf = (DecimalFormat) DecimalFormat
+                .getPercentInstance(Locale.US);
+        nf.setMaximumFractionDigits(3);
+        nf.setMinimumFractionDigits(0);
+        nf.setMultiplier(1);
+
+        double d = 0.005678;
+        String result = nf.format(d);
+        if (!result.equals("0.006%")) {
+            throw new RuntimeException("[Failed while formatting the double"
+                    + " value: " + d + " Expected: 0.006%, Found: " + result
+                    + "]");
+        }
+
+        d = 0.00;
+        result = nf.format(d);
+        if (!result.equals("0%")) {
+            throw new RuntimeException("[Failed while formatting the double"
+                    + " value: " + d + " Expected: 0%, Found: " + result
+                    + "]");
+        }
+
+        d = 0.005678;
+        result = nf.format(d);
+        if (!result.equals("0.006%")) {
+            throw new RuntimeException("[Failed while formatting the double"
+                    + " value: " + d + " Expected: 0.006%, Found: " + result
+                    + "]");
+        }
+
+        //checking with the non zero value
+        d = 0.005678;
+        result = nf.format(d);
+        if (!result.equals("0.006%")) {
+            throw new RuntimeException("[Failed while formatting the double"
+                    + " value: " + d + " Expected: 0.006%, Found: " + result
+                    + "]");
+        }
+
+        d = 9.00;
+        result = nf.format(d);
+        if (!result.equals("9%")) {
+            throw new RuntimeException("[Failed while formatting the double"
+                    + " value: " + d + " Expected: 9%, Found: " + result
+                    + "]");
+        }
+
+        d = 0.005678;
+        result = nf.format(d);
+        if (!result.equals("0.006%")) {
+            throw new RuntimeException("[Failed while formatting the double"
+                    + " value: " + d + " Expected: 0.006%, Found: " + result
+                    + "]");
+        }
+    }
+
+}
+
diff --git a/jdk/test/javax/swing/JTextField/JapaneseReadingAttributes/JapaneseReadingAttributes.java b/jdk/test/javax/swing/JTextField/JapaneseReadingAttributes/JapaneseReadingAttributes.java
new file mode 100644
index 0000000..b7164b9
--- /dev/null
+++ b/jdk/test/javax/swing/JTextField/JapaneseReadingAttributes/JapaneseReadingAttributes.java
@@ -0,0 +1,294 @@
+/*
+ * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+/*
+ * @test
+ * @bug 8176072
+ * @summary Checks whether reading attributes are obtained for Japanese IME
+ * @requires (os.family == "windows")
+ * @run main/manual JapaneseReadingAttributes
+ */
+
+/**
+ * This test requires a manual intervention as the keyboard layout has to be
+ * changed to Japanese IME. Once the keyboard layout has been selected, click on
+ * Start Test to start the automated tests. Will run two passes, first with an
+ * enter key in between to generate the yomigana for the first block of
+ * characters. The second without the intermediate enter key. Without the fix,
+ * there will be a mismatch in the reading attributes obtained.
+ */
+
+import java.awt.BorderLayout;
+import java.awt.Dimension;
+import java.awt.FlowLayout;
+import java.awt.Robot;
+import java.awt.event.InputMethodEvent;
+import java.awt.event.InputMethodListener;
+import java.awt.event.WindowAdapter;
+import java.awt.event.WindowEvent;
+import javax.swing.JButton;
+import javax.swing.JFrame;
+import javax.swing.JPanel;
+import javax.swing.JTextArea;
+import javax.swing.SwingUtilities;
+import javax.swing.WindowConstants;
+import java.awt.event.KeyEvent;
+import java.text.AttributedCharacterIterator;
+import java.util.ArrayList;
+import java.util.concurrent.CountDownLatch;
+import javax.swing.JLabel;
+import javax.swing.JTextField;
+
+public class JapaneseReadingAttributes {
+    private static boolean testPassed = false;
+    private static boolean startTest = false;
+
+    private static JFrame frame = null;
+    private static JLabel lblTestStatus = null;
+    private static JTextField textFieldMain = null;
+    private static JTextField textFieldReading = null;
+    private static String testResult;
+    private static String readingPass1;
+    private static String readingPass2;
+
+    private static final CountDownLatch testStartLatch = new CountDownLatch(1);
+
+    public static void main(String[] args) throws Exception {
+        SwingUtilities.invokeAndWait(() -> {
+            setupUI();
+        });
+
+        testStartLatch.await();
+
+        if (startTest) {
+            glyphTest();
+
+            frame.dispose();
+
+            if (testPassed) {
+                System.out.println(testResult);
+            } else {
+                throw new RuntimeException(testResult);
+            }
+        } else {
+            throw new RuntimeException("User has not executed the test");
+        }
+    }
+
+    private static void setupUI() {
+        String description = " 1. Go to \"Language Preferences -> Add a Language"
+                            + "\" and add \"Japanese\"\n"
+                            + " 2. Set current IM to \"Japanese\" \n"
+                            + " 3. Try typing in the text field to ensure"
+                            + " that Japanese IME has been successfully"
+                            + " selected \n"
+                            + " 4. Now click on \"Start Test\" button \n";
+        String title = "Reading Attributes test Japanese IME (Windows)";
+
+        frame = new JFrame(title);
+
+        JPanel mainPanel = new JPanel(new BorderLayout());
+
+        JPanel textEditPanel = new JPanel(new FlowLayout());
+
+        textFieldMain = new JTextField(20);
+
+        textFieldReading = new JTextField(20);
+        textFieldReading.setEditable(false);
+
+        textEditPanel.add(textFieldMain);
+        textEditPanel.add(textFieldReading);
+
+        mainPanel.add(textEditPanel, BorderLayout.CENTER);
+
+        JTextArea textArea = new JTextArea(description);
+        textArea.setEditable(false);
+        final JButton btnStartTest = new JButton("Start Test");
+        final JButton btnCancelTest = new JButton("Cancel Test");
+
+        btnStartTest.addActionListener((e) -> {
+            btnStartTest.setEnabled(false);
+            btnCancelTest.setEnabled(false);
+            startTest = true;
+            testStartLatch.countDown();
+        });
+
+        btnCancelTest.addActionListener((e) -> {
+            frame.dispose();
+            testStartLatch.countDown();
+        });
+        mainPanel.add(textArea, BorderLayout.NORTH);
+
+        JPanel buttonPanel = new JPanel(new FlowLayout());
+        buttonPanel.add(btnStartTest);
+        buttonPanel.add(btnCancelTest);
+        mainPanel.add(buttonPanel, BorderLayout.SOUTH);
+
+        lblTestStatus = new JLabel("");
+        lblTestStatus.setMinimumSize(new Dimension(250, 20));
+        lblTestStatus.setPreferredSize(new Dimension(250, 20));
+        lblTestStatus.setVisible(true);
+        textEditPanel.add(lblTestStatus);
+
+        frame.add(mainPanel);
+        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
+        frame.pack();
+        frame.setLocationRelativeTo(null);
+
+        frame.addWindowListener(new WindowAdapter() {
+            @Override
+            public void windowClosing(WindowEvent e) {
+                testStartLatch.countDown();
+            }
+            @Override
+            public void windowOpened( WindowEvent e ){
+                textFieldMain.requestFocusInWindow();
+            }
+        });
+
+        textFieldMain.addInputMethodListener(new InputMethodListener() {
+            @Override
+            public void caretPositionChanged(InputMethodEvent event) {
+            }
+
+            @Override
+            public void inputMethodTextChanged(InputMethodEvent event) {
+                AttributedCharacterIterator itr = event.getText();
+                if (itr != null) {
+                    int toCopy = event.getCommittedCharacterCount();
+                    if (toCopy > 0) {
+                        itr.first();
+                        StringBuilder yomigana = new StringBuilder(
+                                textFieldReading.getText());
+                        while (toCopy-- > 0) {
+                            if (itr.getIndex() == itr.getRunStart(
+                                    AttributedCharacterIterator.Attribute.READING)) {
+                                java.text.Annotation annotatedText
+                                        = (java.text.Annotation) itr.
+                                                getAttribute(AttributedCharacterIterator.Attribute.READING);
+                                yomigana.append(annotatedText.getValue());
+                            }
+                            itr.next();
+                        }
+                        textFieldReading.setText(yomigana.toString());
+                    }
+                }
+            }
+        });
+
+        frame.setVisible(true);
+    }
+
+    private static void glyphTest() throws Exception {
+        Robot robotKeySimulator = new Robot();
+        performTasks(robotKeySimulator);
+    }
+
+    public static void performTasks(Robot robotForKeyInput) throws Exception {
+        lblTestStatus.setText("Running Tests..");
+        robotForKeyInput.setAutoDelay(500);
+
+        ArrayList<Integer> keyCodesToUse = new ArrayList<Integer>();
+
+        keyCodesToUse.add(KeyEvent.VK_A);
+        keyCodesToUse.add(KeyEvent.VK_B);
+        keyCodesToUse.add(KeyEvent.VK_E);
+        keyCodesToUse.add(KeyEvent.VK_SPACE);
+        keyCodesToUse.add(KeyEvent.VK_SPACE);
+        keyCodesToUse.add(KeyEvent.VK_ENTER);
+        keyCodesToUse.add(KeyEvent.VK_S);
+        keyCodesToUse.add(KeyEvent.VK_I);
+        keyCodesToUse.add(KeyEvent.VK_N);
+        keyCodesToUse.add(KeyEvent.VK_Z);
+        keyCodesToUse.add(KeyEvent.VK_O);
+        keyCodesToUse.add(KeyEvent.VK_U);
+        keyCodesToUse.add(KeyEvent.VK_SPACE);
+        keyCodesToUse.add(KeyEvent.VK_ENTER);
+
+        textFieldMain.requestFocusInWindow();
+
+        robotForKeyInput.waitForIdle();
+
+        enterInput(robotForKeyInput, keyCodesToUse);
+
+        SwingUtilities.invokeAndWait(() -> {
+            readingPass1 = textFieldReading.getText();
+        });
+
+        if (setTaskStatus(readingPass1, 1)) {
+            keyCodesToUse.remove((Integer) KeyEvent.VK_ENTER);
+
+            enterInput(robotForKeyInput, keyCodesToUse);
+
+            SwingUtilities.invokeAndWait(() -> {
+                readingPass2 = textFieldReading.getText();
+            });
+
+            if (setTaskStatus(readingPass2, 2)) {
+                if (readingPass1.equals(readingPass2)) {
+                    testPassed = true;
+                    testResult = "Test Passed : Same reading attribute "
+                            + "obtained from both passes ";
+                    lblTestStatus.setText(testResult);
+                } else {
+                    testResult = "Test Failed : Reading attribute from Pass 1 <"
+                            + readingPass1 + "> != Reading attribute "
+                            + "from Pass 2 <" + readingPass2 + ">";
+                }
+            }
+        }
+    }
+
+    private static void enterInput(Robot robotKeyInput,
+            ArrayList<Integer> keyInputs) {
+        textFieldReading.setText("");
+        textFieldMain.setText("");
+
+        String strKeyInput = "KeyPress=>";
+        int nOfKeyInputs = keyInputs.size();
+        for (int i = 0; i < nOfKeyInputs; i++) {
+            int keyToUse = keyInputs.get(i);
+            robotKeyInput.keyPress(keyToUse);
+            robotKeyInput.keyRelease(keyToUse);
+            strKeyInput += (Integer.toHexString(keyToUse)) + ":";
+        }
+
+        System.out.println(strKeyInput);
+    }
+
+    public static boolean setTaskStatus(String readingValue, int passCount) {
+        boolean status = false;
+
+        if (!readingValue.isEmpty()) {
+            testResult = "Attribute : " + readingValue
+                    + "read from pass " + Integer.toString(passCount);
+            status = true;
+        } else {
+            testResult = "Failed to read Reading attribute from pass  "
+                    + Integer.toString(passCount);
+        }
+
+        lblTestStatus.setText(testResult);
+
+        return status;
+    }
+}
diff --git a/jdk/test/sun/security/krb5/auto/AcceptPermissions.java b/jdk/test/sun/security/krb5/auto/AcceptPermissions.java
index d26f968..9f006a6 100644
--- a/jdk/test/sun/security/krb5/auto/AcceptPermissions.java
+++ b/jdk/test/sun/security/krb5/auto/AcceptPermissions.java
@@ -26,8 +26,8 @@
  * @bug 9999999
  * @summary default principal can act as anyone
  * @compile -XDignore.symbol.file AcceptPermissions.java
- * @run main/othervm AcceptPermissions two
- * @run main/othervm AcceptPermissions unbound
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock AcceptPermissions two
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock AcceptPermissions unbound
  */
 
 import java.nio.file.Files;
diff --git a/jdk/test/sun/security/krb5/auto/AcceptorSubKey.java b/jdk/test/sun/security/krb5/auto/AcceptorSubKey.java
index f5e122d..2f322d0 100644
--- a/jdk/test/sun/security/krb5/auto/AcceptorSubKey.java
+++ b/jdk/test/sun/security/krb5/auto/AcceptorSubKey.java
@@ -26,8 +26,8 @@
  * @bug 7077646
  * @summary gssapi wrap for CFX per-message tokens always set FLAG_ACCEPTOR_SUBKEY
  * @compile -XDignore.symbol.file AcceptorSubKey.java
- * @run main/othervm AcceptorSubKey 0
- * @run main/othervm AcceptorSubKey 4
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock AcceptorSubKey 0
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock AcceptorSubKey 4
  */
 
 import sun.security.jgss.GSSUtil;
diff --git a/jdk/test/sun/security/krb5/auto/AddressesAndNameType.java b/jdk/test/sun/security/krb5/auto/AddressesAndNameType.java
index de0dc89..6df095e 100644
--- a/jdk/test/sun/security/krb5/auto/AddressesAndNameType.java
+++ b/jdk/test/sun/security/krb5/auto/AddressesAndNameType.java
@@ -24,9 +24,9 @@
 /*
  * @test
  * @bug 4501327 4868379 8039132
- * @run main/othervm AddressesAndNameType 1
- * @run main/othervm AddressesAndNameType 2
- * @run main/othervm AddressesAndNameType 3
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock AddressesAndNameType 1
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock AddressesAndNameType 2
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock AddressesAndNameType 3
  * @summary noaddresses settings and server name type
  */
 
diff --git a/jdk/test/sun/security/krb5/auto/BadKdc1.java b/jdk/test/sun/security/krb5/auto/BadKdc1.java
index dd60893..0170cd3 100644
--- a/jdk/test/sun/security/krb5/auto/BadKdc1.java
+++ b/jdk/test/sun/security/krb5/auto/BadKdc1.java
@@ -24,7 +24,7 @@
 /*
  * @test
  * @bug 6843127
- * @run main/othervm/timeout=300 BadKdc1
+ * @run main/othervm/timeout=300 -Dsun.net.spi.nameservice.provider.1=ns,mock BadKdc1
  * @summary krb5 should not try to access unavailable kdc too often
  */
 
diff --git a/jdk/test/sun/security/krb5/auto/BadKdc2.java b/jdk/test/sun/security/krb5/auto/BadKdc2.java
index 4291d5c..218aa7b 100644
--- a/jdk/test/sun/security/krb5/auto/BadKdc2.java
+++ b/jdk/test/sun/security/krb5/auto/BadKdc2.java
@@ -24,7 +24,7 @@
 /*
  * @test
  * @bug 6843127
- * @run main/othervm/timeout=300 BadKdc2
+ * @run main/othervm/timeout=300 -Dsun.net.spi.nameservice.provider.1=ns,mock BadKdc2
  * @summary krb5 should not try to access unavailable kdc too often
  */
 
diff --git a/jdk/test/sun/security/krb5/auto/BadKdc3.java b/jdk/test/sun/security/krb5/auto/BadKdc3.java
index 4bafd9a..d5c5f87 100644
--- a/jdk/test/sun/security/krb5/auto/BadKdc3.java
+++ b/jdk/test/sun/security/krb5/auto/BadKdc3.java
@@ -24,7 +24,7 @@
 /*
  * @test
  * @bug 6843127
- * @run main/othervm/timeout=300 BadKdc3
+ * @run main/othervm/timeout=300 -Dsun.net.spi.nameservice.provider.1=ns,mock BadKdc3
  * @summary krb5 should not try to access unavailable kdc too often
  */
 
diff --git a/jdk/test/sun/security/krb5/auto/BadKdc4.java b/jdk/test/sun/security/krb5/auto/BadKdc4.java
index 877e540..14f078e 100644
--- a/jdk/test/sun/security/krb5/auto/BadKdc4.java
+++ b/jdk/test/sun/security/krb5/auto/BadKdc4.java
@@ -24,7 +24,7 @@
 /*
  * @test
  * @bug 6843127
- * @run main/othervm/timeout=300 BadKdc4
+ * @run main/othervm/timeout=300 -Dsun.net.spi.nameservice.provider.1=ns,mock BadKdc4
  * @summary krb5 should not try to access unavailable kdc too often
  */
 
diff --git a/jdk/test/sun/security/krb5/auto/Basic.java b/jdk/test/sun/security/krb5/auto/Basic.java
index ef7f11d..7ec3873 100644
--- a/jdk/test/sun/security/krb5/auto/Basic.java
+++ b/jdk/test/sun/security/krb5/auto/Basic.java
@@ -26,7 +26,7 @@
  * @bug 7152176
  * @summary More krb5 tests
  * @compile -XDignore.symbol.file Basic.java
- * @run main/othervm Basic
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock Basic
  */
 
 import sun.security.jgss.GSSUtil;
diff --git a/jdk/test/sun/security/krb5/auto/BasicKrb5Test.java b/jdk/test/sun/security/krb5/auto/BasicKrb5Test.java
index 3a60cc2..ade0b54 100644
--- a/jdk/test/sun/security/krb5/auto/BasicKrb5Test.java
+++ b/jdk/test/sun/security/krb5/auto/BasicKrb5Test.java
@@ -26,34 +26,34 @@
  * @bug 6706974
  * @summary Add krb5 test infrastructure
  * @compile -XDignore.symbol.file BasicKrb5Test.java
- * @run main/othervm BasicKrb5Test
- * @run main/othervm BasicKrb5Test des-cbc-crc
- * @run main/othervm BasicKrb5Test des-cbc-md5
- * @run main/othervm BasicKrb5Test des3-cbc-sha1
- * @run main/othervm BasicKrb5Test aes128-cts
- * @run main/othervm BasicKrb5Test aes256-cts
- * @run main/othervm BasicKrb5Test rc4-hmac
- * @run main/othervm BasicKrb5Test -s
- * @run main/othervm BasicKrb5Test des-cbc-crc -s
- * @run main/othervm BasicKrb5Test des-cbc-md5 -s
- * @run main/othervm BasicKrb5Test des3-cbc-sha1 -s
- * @run main/othervm BasicKrb5Test aes128-cts -s
- * @run main/othervm BasicKrb5Test aes256-cts -s
- * @run main/othervm BasicKrb5Test rc4-hmac -s
- * @run main/othervm BasicKrb5Test -C
- * @run main/othervm BasicKrb5Test des-cbc-crc -C
- * @run main/othervm BasicKrb5Test des-cbc-md5 -C
- * @run main/othervm BasicKrb5Test des3-cbc-sha1 -C
- * @run main/othervm BasicKrb5Test aes128-cts -C
- * @run main/othervm BasicKrb5Test aes256-cts -C
- * @run main/othervm BasicKrb5Test rc4-hmac -C
- * @run main/othervm BasicKrb5Test -s -C
- * @run main/othervm BasicKrb5Test des-cbc-crc -s -C
- * @run main/othervm BasicKrb5Test des-cbc-md5 -s -C
- * @run main/othervm BasicKrb5Test des3-cbc-sha1 -s -C
- * @run main/othervm BasicKrb5Test aes128-cts -s -C
- * @run main/othervm BasicKrb5Test aes256-cts -s -C
- * @run main/othervm BasicKrb5Test rc4-hmac -s -C
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock BasicKrb5Test
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock BasicKrb5Test des-cbc-crc
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock BasicKrb5Test des-cbc-md5
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock BasicKrb5Test des3-cbc-sha1
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock BasicKrb5Test aes128-cts
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock BasicKrb5Test aes256-cts
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock BasicKrb5Test rc4-hmac
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock BasicKrb5Test -s
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock BasicKrb5Test des-cbc-crc -s
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock BasicKrb5Test des-cbc-md5 -s
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock BasicKrb5Test des3-cbc-sha1 -s
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock BasicKrb5Test aes128-cts -s
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock BasicKrb5Test aes256-cts -s
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock BasicKrb5Test rc4-hmac -s
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock BasicKrb5Test -C
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock BasicKrb5Test des-cbc-crc -C
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock BasicKrb5Test des-cbc-md5 -C
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock BasicKrb5Test des3-cbc-sha1 -C
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock BasicKrb5Test aes128-cts -C
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock BasicKrb5Test aes256-cts -C
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock BasicKrb5Test rc4-hmac -C
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock BasicKrb5Test -s -C
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock BasicKrb5Test des-cbc-crc -s -C
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock BasicKrb5Test des-cbc-md5 -s -C
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock BasicKrb5Test des3-cbc-sha1 -s -C
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock BasicKrb5Test aes128-cts -s -C
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock BasicKrb5Test aes256-cts -s -C
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock BasicKrb5Test rc4-hmac -s -C
  */
 
 import org.ietf.jgss.GSSName;
diff --git a/jdk/test/sun/security/krb5/auto/BasicProc.java b/jdk/test/sun/security/krb5/auto/BasicProc.java
index 54b204f..bcc3cd0 100644
--- a/jdk/test/sun/security/krb5/auto/BasicProc.java
+++ b/jdk/test/sun/security/krb5/auto/BasicProc.java
@@ -27,7 +27,7 @@
  * @summary A test library to launch multiple Java processes
  * @library ../../../../java/security/testlibrary/
  * @compile -XDignore.symbol.file BasicProc.java
- * @run main/othervm BasicProc
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock BasicProc
  */
 
 import java.io.File;
@@ -65,6 +65,9 @@
                     .args("client")
                     .prop("java.security.krb5.conf", CONF)
                     .prop("java.security.manager", "")
+                    .prop("sun.net.spi.nameservice.provider.1", "ns,mock")
+                    .perm(new java.lang.RuntimePermission(
+                            "accessClassInPackage.sun.net.spi.nameservice"))
                     .perm(new java.util.PropertyPermission(
                             "sun.security.krb5.principal", "read"))
                     .perm(new javax.security.auth.AuthPermission(
@@ -85,6 +88,9 @@
                     .args("server")
                     .prop("java.security.krb5.conf", CONF)
                     .prop("java.security.manager", "")
+                    .prop("sun.net.spi.nameservice.provider.1", "ns,mock")
+                    .perm(new java.lang.RuntimePermission(
+                            "accessClassInPackage.sun.net.spi.nameservice"))
                     .perm(new java.util.PropertyPermission(
                             "sun.security.krb5.principal", "read"))
                     .perm(new javax.security.auth.AuthPermission(
@@ -107,6 +113,9 @@
                     .args("backend")
                     .prop("java.security.krb5.conf", CONF)
                     .prop("java.security.manager", "")
+                    .prop("sun.net.spi.nameservice.provider.1", "ns,mock")
+                    .perm(new java.lang.RuntimePermission(
+                            "accessClassInPackage.sun.net.spi.nameservice"))
                     .perm(new java.util.PropertyPermission(
                             "sun.security.krb5.principal", "read"))
                     .perm(new javax.security.auth.AuthPermission(
@@ -185,6 +194,7 @@
         return p
             .env("KRB5_CONFIG", CONF)
             .env("KRB5_KTNAME", KTAB)
+            .prop("sun.net.spi.nameservice.provider.1", "ns,mock")
             .prop("sun.security.jgss.native", "true")
             .prop("javax.security.auth.useSubjectCredsOnly", "false")
             .prop("sun.security.nativegss.debug", "true");
diff --git a/jdk/test/sun/security/krb5/auto/BogusKDC.java b/jdk/test/sun/security/krb5/auto/BogusKDC.java
index 15d9add..4b42230 100644
--- a/jdk/test/sun/security/krb5/auto/BogusKDC.java
+++ b/jdk/test/sun/security/krb5/auto/BogusKDC.java
@@ -36,7 +36,7 @@
  * @bug 4515853 8075297
  * @summary Checks that Kerberos client tries slave KDC
  *          if master KDC is not responding
- * @run main/othervm BogusKDC
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock BogusKDC
  */
 public class BogusKDC {
 
diff --git a/jdk/test/sun/security/krb5/auto/CleanState.java b/jdk/test/sun/security/krb5/auto/CleanState.java
index b63e23d..2c88503 100644
--- a/jdk/test/sun/security/krb5/auto/CleanState.java
+++ b/jdk/test/sun/security/krb5/auto/CleanState.java
@@ -25,7 +25,7 @@
  * @test
  * @bug 6716534
  * @compile -XDignore.symbol.file CleanState.java
- * @run main/othervm CleanState
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock CleanState
  * @summary Krb5LoginModule has not cleaned temp info between authentication attempts
  */
 import com.sun.security.auth.module.Krb5LoginModule;
diff --git a/jdk/test/sun/security/krb5/auto/CrossRealm.java b/jdk/test/sun/security/krb5/auto/CrossRealm.java
index 26dc6ae..823acc3 100644
--- a/jdk/test/sun/security/krb5/auto/CrossRealm.java
+++ b/jdk/test/sun/security/krb5/auto/CrossRealm.java
@@ -25,7 +25,7 @@
  * @test
  * @bug 6706974
  * @compile -XDignore.symbol.file CrossRealm.java
- * @run main/othervm CrossRealm
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock CrossRealm
  * @summary Add krb5 test infrastructure
  */
 import java.io.File;
diff --git a/jdk/test/sun/security/krb5/auto/DiffNameSameKey.java b/jdk/test/sun/security/krb5/auto/DiffNameSameKey.java
index 38bacb8..d77d48c 100644
--- a/jdk/test/sun/security/krb5/auto/DiffNameSameKey.java
+++ b/jdk/test/sun/security/krb5/auto/DiffNameSameKey.java
@@ -26,8 +26,8 @@
  * @bug 8005447
  * @summary default principal can act as anyone
  * @compile -XDignore.symbol.file DiffNameSameKey.java
- * @run main/othervm/fail DiffNameSameKey a
- * @run main/othervm DiffNameSameKey b
+ * @run main/othervm/fail -Dsun.net.spi.nameservice.provider.1=ns,mock DiffNameSameKey a
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock DiffNameSameKey b
  */
 
 import sun.security.jgss.GSSUtil;
diff --git a/jdk/test/sun/security/krb5/auto/DupEtypes.java b/jdk/test/sun/security/krb5/auto/DupEtypes.java
index efc26e8..a59c995 100644
--- a/jdk/test/sun/security/krb5/auto/DupEtypes.java
+++ b/jdk/test/sun/security/krb5/auto/DupEtypes.java
@@ -26,11 +26,11 @@
  * @bug 7067974
  * @summary multiple ETYPE-INFO-ENTRY with same etype and different salt
  * @compile -XDignore.symbol.file DupEtypes.java
- * @run main/othervm DupEtypes 1
- * @run main/othervm DupEtypes 2
- * @run main/othervm/fail DupEtypes 3
- * @run main/othervm DupEtypes 4
- * @run main/othervm DupEtypes 5
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock DupEtypes 1
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock DupEtypes 2
+ * @run main/othervm/fail -Dsun.net.spi.nameservice.provider.1=ns,mock DupEtypes 3
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock DupEtypes 4
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock DupEtypes 5
  */
 
 import sun.security.jgss.GSSUtil;
diff --git a/jdk/test/sun/security/krb5/auto/DynamicKeytab.java b/jdk/test/sun/security/krb5/auto/DynamicKeytab.java
index dd9e67c..927a37a 100644
--- a/jdk/test/sun/security/krb5/auto/DynamicKeytab.java
+++ b/jdk/test/sun/security/krb5/auto/DynamicKeytab.java
@@ -25,7 +25,7 @@
  * @test
  * @bug 6894072
  * @compile -XDignore.symbol.file DynamicKeytab.java
- * @run main/othervm DynamicKeytab
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock DynamicKeytab
  * @summary always refresh keytab
  */
 
diff --git a/jdk/test/sun/security/krb5/auto/EmptyPassword.java b/jdk/test/sun/security/krb5/auto/EmptyPassword.java
index d66b202..3e287eb 100644
--- a/jdk/test/sun/security/krb5/auto/EmptyPassword.java
+++ b/jdk/test/sun/security/krb5/auto/EmptyPassword.java
@@ -26,7 +26,7 @@
  * @bug 6879540
  * @summary enable empty password for kerberos 5
  * @compile -XDignore.symbol.file EmptyPassword.java
- * @run main/othervm EmptyPassword
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock EmptyPassword
  */
 
 public class EmptyPassword {
diff --git a/jdk/test/sun/security/krb5/auto/FileKeyTab.java b/jdk/test/sun/security/krb5/auto/FileKeyTab.java
index a8e8377..01cdfa4 100644
--- a/jdk/test/sun/security/krb5/auto/FileKeyTab.java
+++ b/jdk/test/sun/security/krb5/auto/FileKeyTab.java
@@ -26,7 +26,7 @@
  * @bug 7152121
  * @summary Krb5LoginModule no longer handles keyTabNames with "file:" prefix
  * @compile -XDignore.symbol.file FileKeyTab.java
- * @run main/othervm FileKeyTab
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock FileKeyTab
  */
 
 import java.io.File;
diff --git a/jdk/test/sun/security/krb5/auto/ForwardableCheck.java b/jdk/test/sun/security/krb5/auto/ForwardableCheck.java
index df6e49e..11f7ad7 100644
--- a/jdk/test/sun/security/krb5/auto/ForwardableCheck.java
+++ b/jdk/test/sun/security/krb5/auto/ForwardableCheck.java
@@ -26,7 +26,7 @@
  * @bug 8022582
  * @summary Relax response flags checking in sun.security.krb5.KrbKdcRep.check.
  * @compile -XDignore.symbol.file ForwardableCheck.java
- * @run main/othervm ForwardableCheck
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock ForwardableCheck
  */
 
 import org.ietf.jgss.GSSException;
diff --git a/jdk/test/sun/security/krb5/auto/GSS.java b/jdk/test/sun/security/krb5/auto/GSS.java
index 8e78209..782d162 100644
--- a/jdk/test/sun/security/krb5/auto/GSS.java
+++ b/jdk/test/sun/security/krb5/auto/GSS.java
@@ -26,7 +26,7 @@
  * @bug 7152176
  * @summary More krb5 tests
  * @compile -XDignore.symbol.file GSS.java
- * @run main/othervm GSS
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock GSS
  */
 
 import sun.security.jgss.GSSUtil;
diff --git a/jdk/test/sun/security/krb5/auto/GSSUnbound.java b/jdk/test/sun/security/krb5/auto/GSSUnbound.java
index 74f0e9a..336c570 100644
--- a/jdk/test/sun/security/krb5/auto/GSSUnbound.java
+++ b/jdk/test/sun/security/krb5/auto/GSSUnbound.java
@@ -26,7 +26,7 @@
  * @bug 8001104
  * @summary Unbound SASL service: the GSSAPI/krb5 mech
  * @compile -XDignore.symbol.file GSSUnbound.java
- * @run main/othervm GSSUnbound
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock GSSUnbound
  */
 
 import java.security.Security;
diff --git a/jdk/test/sun/security/krb5/auto/HttpNegotiateServer.java b/jdk/test/sun/security/krb5/auto/HttpNegotiateServer.java
index 4da7cfa..0e766bb 100644
--- a/jdk/test/sun/security/krb5/auto/HttpNegotiateServer.java
+++ b/jdk/test/sun/security/krb5/auto/HttpNegotiateServer.java
@@ -24,7 +24,7 @@
 /*
  * @test
  * @bug 6578647 6829283
- * @run main/othervm HttpNegotiateServer
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock HttpNegotiateServer
  * @summary Undefined requesting URL in java.net.Authenticator.getPasswordAuthentication()
  * @summary HTTP/Negotiate: Authenticator triggered again when user cancels the first one
  */
diff --git a/jdk/test/sun/security/krb5/auto/IgnoreChannelBinding.java b/jdk/test/sun/security/krb5/auto/IgnoreChannelBinding.java
index e2641a9..2fe23a2 100644
--- a/jdk/test/sun/security/krb5/auto/IgnoreChannelBinding.java
+++ b/jdk/test/sun/security/krb5/auto/IgnoreChannelBinding.java
@@ -24,7 +24,7 @@
 /*
  * @test
  * @bug 6851973
- * @run main/othervm IgnoreChannelBinding
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock IgnoreChannelBinding
  * @summary ignore incoming channel binding if acceptor does not set one
  */
 
diff --git a/jdk/test/sun/security/krb5/auto/KDC.java b/jdk/test/sun/security/krb5/auto/KDC.java
index 05a271b..2e30a1f 100644
--- a/jdk/test/sun/security/krb5/auto/KDC.java
+++ b/jdk/test/sun/security/krb5/auto/KDC.java
@@ -206,9 +206,9 @@
         SENSITIVE_ACCOUNTS,
     };
 
-    static {
-        System.setProperty("sun.net.spi.nameservice.provider.1", "ns,mock");
-    }
+    //static {
+    //    System.setProperty("sun.net.spi.nameservice.provider.1", "ns,mock");
+    //}
 
     /**
      * A standalone KDC server.
diff --git a/jdk/test/sun/security/krb5/auto/KPEquals.java b/jdk/test/sun/security/krb5/auto/KPEquals.java
index 7a7aaa3..870b7a2 100644
--- a/jdk/test/sun/security/krb5/auto/KPEquals.java
+++ b/jdk/test/sun/security/krb5/auto/KPEquals.java
@@ -26,7 +26,7 @@
  * @bug 8015669
  * @summary KerberosPrincipal::equals should ignore name-type
  * @compile -XDignore.symbol.file KPEquals.java
- * @run main/othervm KPEquals
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock KPEquals
  */
 
 import sun.security.jgss.GSSUtil;
diff --git a/jdk/test/sun/security/krb5/auto/KerberosHashEqualsTest.java b/jdk/test/sun/security/krb5/auto/KerberosHashEqualsTest.java
index e7c026d..c666cb4 100644
--- a/jdk/test/sun/security/krb5/auto/KerberosHashEqualsTest.java
+++ b/jdk/test/sun/security/krb5/auto/KerberosHashEqualsTest.java
@@ -24,7 +24,7 @@
 /*
  * @test
  * @bug 4641821
- * @run main/othervm KerberosHashEqualsTest
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock KerberosHashEqualsTest
  * @summary hashCode() and equals() for KerberosKey and KerberosTicket
  */
 
diff --git a/jdk/test/sun/security/krb5/auto/KeyPermissions.java b/jdk/test/sun/security/krb5/auto/KeyPermissions.java
index 78f0eaf..876346e 100644
--- a/jdk/test/sun/security/krb5/auto/KeyPermissions.java
+++ b/jdk/test/sun/security/krb5/auto/KeyPermissions.java
@@ -26,7 +26,7 @@
  * @bug 8004488
  * @summary wrong permissions checked in krb5
  * @compile -XDignore.symbol.file KeyPermissions.java
- * @run main/othervm KeyPermissions
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock KeyPermissions
  */
 
 import java.security.AccessControlException;
diff --git a/jdk/test/sun/security/krb5/auto/KeyTabCompat.java b/jdk/test/sun/security/krb5/auto/KeyTabCompat.java
index 00a7f7c..6d1bc8b 100644
--- a/jdk/test/sun/security/krb5/auto/KeyTabCompat.java
+++ b/jdk/test/sun/security/krb5/auto/KeyTabCompat.java
@@ -26,7 +26,7 @@
  * @bug 6894072
  * @bug 8004488
  * @compile -XDignore.symbol.file KeyTabCompat.java
- * @run main/othervm KeyTabCompat
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock KeyTabCompat
  * @summary always refresh keytab
  */
 
diff --git a/jdk/test/sun/security/krb5/auto/KrbTicket.java b/jdk/test/sun/security/krb5/auto/KrbTicket.java
index daed1cc..e822b39 100644
--- a/jdk/test/sun/security/krb5/auto/KrbTicket.java
+++ b/jdk/test/sun/security/krb5/auto/KrbTicket.java
@@ -37,7 +37,7 @@
  * @test
  * @bug 6857795 8075299
  * @summary Checks Kerberos ticket properties
- * @run main/othervm KrbTicket
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock KrbTicket
  */
 public class KrbTicket {
 
diff --git a/jdk/test/sun/security/krb5/auto/KvnoNA.java b/jdk/test/sun/security/krb5/auto/KvnoNA.java
index 2c645ec..747a81f 100644
--- a/jdk/test/sun/security/krb5/auto/KvnoNA.java
+++ b/jdk/test/sun/security/krb5/auto/KvnoNA.java
@@ -25,7 +25,7 @@
  * @test
  * @bug 7197159
  * @compile -XDignore.symbol.file KvnoNA.java
- * @run main/othervm KvnoNA
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock KvnoNA
  * @summary accept different kvno if there no match
  */
 
diff --git a/jdk/test/sun/security/krb5/auto/LifeTimeInSeconds.java b/jdk/test/sun/security/krb5/auto/LifeTimeInSeconds.java
index 9c518ff..9d4c6d7 100644
--- a/jdk/test/sun/security/krb5/auto/LifeTimeInSeconds.java
+++ b/jdk/test/sun/security/krb5/auto/LifeTimeInSeconds.java
@@ -24,7 +24,7 @@
 /*
  * @test
  * @bug 6857802
- * @run main/othervm LifeTimeInSeconds
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock LifeTimeInSeconds
  * @summary GSS getRemainingInitLifetime method returns milliseconds not seconds
  */
 import org.ietf.jgss.GSSCredential;
diff --git a/jdk/test/sun/security/krb5/auto/LoginModuleOptions.java b/jdk/test/sun/security/krb5/auto/LoginModuleOptions.java
index 2c77451..a3a4e43 100644
--- a/jdk/test/sun/security/krb5/auto/LoginModuleOptions.java
+++ b/jdk/test/sun/security/krb5/auto/LoginModuleOptions.java
@@ -24,7 +24,7 @@
 /*
  * @test
  * @bug 6765491
- * @run main/othervm LoginModuleOptions
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock LoginModuleOptions
  * @summary Krb5LoginModule a little too restrictive, and the doc is not clear.
  */
 import com.sun.security.auth.module.Krb5LoginModule;
diff --git a/jdk/test/sun/security/krb5/auto/LoginNoPass.java b/jdk/test/sun/security/krb5/auto/LoginNoPass.java
index 73de940..d67f1b6 100644
--- a/jdk/test/sun/security/krb5/auto/LoginNoPass.java
+++ b/jdk/test/sun/security/krb5/auto/LoginNoPass.java
@@ -26,7 +26,7 @@
  * @bug 8028351
  * @summary JWS doesn't get authenticated when using kerberos auth proxy
  * @compile -XDignore.symbol.file LoginNoPass.java
- * @run main/othervm LoginNoPass
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock LoginNoPass
  */
 
 import sun.security.jgss.GSSUtil;
diff --git a/jdk/test/sun/security/krb5/auto/MSOID2.java b/jdk/test/sun/security/krb5/auto/MSOID2.java
index e81be6a..948718c 100644
--- a/jdk/test/sun/security/krb5/auto/MSOID2.java
+++ b/jdk/test/sun/security/krb5/auto/MSOID2.java
@@ -26,7 +26,7 @@
  * @bug 8078439
  * @summary SPNEGO auth fails if client proposes MS krb5 OID
  * @compile -XDignore.symbol.file MSOID2.java
- * @run main/othervm MSOID2
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock MSOID2
  */
 
 import sun.security.jgss.GSSUtil;
diff --git a/jdk/test/sun/security/krb5/auto/MaxRetries.java b/jdk/test/sun/security/krb5/auto/MaxRetries.java
index 2de3817..de0d175 100644
--- a/jdk/test/sun/security/krb5/auto/MaxRetries.java
+++ b/jdk/test/sun/security/krb5/auto/MaxRetries.java
@@ -25,7 +25,7 @@
  * @test
  * @bug 6844193
  * @compile -XDignore.symbol.file MaxRetries.java
- * @run main/othervm/timeout=300 MaxRetries
+ * @run main/othervm/timeout=300 -Dsun.net.spi.nameservice.provider.1=ns,mock MaxRetries
  * @summary support max_retries in krb5.conf
  */
 
diff --git a/jdk/test/sun/security/krb5/auto/MoreKvno.java b/jdk/test/sun/security/krb5/auto/MoreKvno.java
index 8abb1e2..ca67abc 100644
--- a/jdk/test/sun/security/krb5/auto/MoreKvno.java
+++ b/jdk/test/sun/security/krb5/auto/MoreKvno.java
@@ -24,7 +24,7 @@
 /*
  * @test
  * @bug 6893158 6907425 7197159
- * @run main/othervm MoreKvno
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock MoreKvno
  * @summary AP_REQ check should use key version number
  */
 
diff --git a/jdk/test/sun/security/krb5/auto/NewSalt.java b/jdk/test/sun/security/krb5/auto/NewSalt.java
index 2a0a17f..6101ebf 100644
--- a/jdk/test/sun/security/krb5/auto/NewSalt.java
+++ b/jdk/test/sun/security/krb5/auto/NewSalt.java
@@ -25,9 +25,9 @@
  * @test
  * @bug 6960894
  * @summary Better AS-REQ creation and processing
- * @run main/othervm NewSalt
- * @run main/othervm -Dnopreauth NewSalt
- * @run main/othervm -Donlyonepreauth NewSalt
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock NewSalt
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock -Dnopreauth NewSalt
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock -Donlyonepreauth NewSalt
  */
 
 import sun.security.jgss.GSSUtil;
diff --git a/jdk/test/sun/security/krb5/auto/NoAddresses.java b/jdk/test/sun/security/krb5/auto/NoAddresses.java
index 04c5b71..7a8cc7b 100644
--- a/jdk/test/sun/security/krb5/auto/NoAddresses.java
+++ b/jdk/test/sun/security/krb5/auto/NoAddresses.java
@@ -24,9 +24,9 @@
 /*
  * @test
  * @bug 7032354
- * @run main/othervm NoAddresses 1
- * @run main/othervm NoAddresses 2
- * @run main/othervm/fail NoAddresses 3
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock NoAddresses 1
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock NoAddresses 2
+ * @run main/othervm/fail -Dsun.net.spi.nameservice.provider.1=ns,mock NoAddresses 3
  * @summary no-addresses should not be used on acceptor side
  */
 
diff --git a/jdk/test/sun/security/krb5/auto/NoInitNoKeytab.java b/jdk/test/sun/security/krb5/auto/NoInitNoKeytab.java
index cde2ec6..7544846 100644
--- a/jdk/test/sun/security/krb5/auto/NoInitNoKeytab.java
+++ b/jdk/test/sun/security/krb5/auto/NoInitNoKeytab.java
@@ -26,7 +26,7 @@
  * @bug 7089889
  * @summary Krb5LoginModule.login() throws an exception if used without a keytab
  * @compile -XDignore.symbol.file NoInitNoKeytab.java
- * @run main/othervm NoInitNoKeytab
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock NoInitNoKeytab
  */
 
 import java.io.FileOutputStream;
diff --git a/jdk/test/sun/security/krb5/auto/NonMutualSpnego.java b/jdk/test/sun/security/krb5/auto/NonMutualSpnego.java
index 304dca1b..cd9d9bd 100644
--- a/jdk/test/sun/security/krb5/auto/NonMutualSpnego.java
+++ b/jdk/test/sun/security/krb5/auto/NonMutualSpnego.java
@@ -24,7 +24,7 @@
 /*
  * @test
  * @bug 6733095
- * @run main/othervm NonMutualSpnego
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock NonMutualSpnego
  * @summary Failure when SPNEGO request non-Mutual
  */
 
diff --git a/jdk/test/sun/security/krb5/auto/NoneReplayCacheTest.java b/jdk/test/sun/security/krb5/auto/NoneReplayCacheTest.java
index 2bb59a2..9168b5d 100644
--- a/jdk/test/sun/security/krb5/auto/NoneReplayCacheTest.java
+++ b/jdk/test/sun/security/krb5/auto/NoneReplayCacheTest.java
@@ -24,7 +24,7 @@
 /*
  * @test
  * @bug 8001326
- * @run main/othervm NoneReplayCacheTest
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock NoneReplayCacheTest
  * @summary the replaycache type none cannot stop an authenticator replay,
  * but it can stop a message replay when s.s.k.acceptor.subkey is true.
  * You should not really use none in production environment. This test merely
diff --git a/jdk/test/sun/security/krb5/auto/OkAsDelegate.java b/jdk/test/sun/security/krb5/auto/OkAsDelegate.java
index d66e242..fe4868a 100644
--- a/jdk/test/sun/security/krb5/auto/OkAsDelegate.java
+++ b/jdk/test/sun/security/krb5/auto/OkAsDelegate.java
@@ -24,27 +24,27 @@
 /*
  * @test
  * @bug 6853328 7172701
- * @run main/othervm OkAsDelegate false true true false false false
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock OkAsDelegate false true true false false false
  *      FORWARDABLE ticket not allowed, always fail
- * @run main/othervm OkAsDelegate true false false false false false
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock OkAsDelegate true false false false false false
  *      Service ticket no OK-AS-DELEGATE. Request nothing, gain nothing
- * @run main/othervm OkAsDelegate true false true false false false
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock OkAsDelegate true false true false false false
  *      Service ticket no OK-AS-DELEGATE. Request deleg policy, gain nothing
- * @run main/othervm OkAsDelegate true true false true false true
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock OkAsDelegate true true false true false true
  *      Service ticket no OK-AS-DELEGATE. Request deleg, granted
- * @run main/othervm OkAsDelegate true true true true false true
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock OkAsDelegate true true true true false true
  *      Service ticket no OK-AS-DELEGATE. Request deleg and deleg policy, granted, with info not by policy
- * @run main/othervm -Dtest.kdc.policy.ok-as-delegate OkAsDelegate true false true true true true
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock -Dtest.kdc.policy.ok-as-delegate OkAsDelegate true false true true true true
  *      Service ticket has OK-AS-DELEGATE. Request deleg policy, granted
- * @run main/othervm -Dtest.kdc.policy.ok-as-delegate OkAsDelegate true true true true true true
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock -Dtest.kdc.policy.ok-as-delegate OkAsDelegate true true true true true true
  *      Service ticket has OK-AS-DELEGATE. granted, with info by policy
- * @run main/othervm -Dtest.spnego OkAsDelegate false true true false false false
- * @run main/othervm -Dtest.spnego OkAsDelegate true false false false false false
- * @run main/othervm -Dtest.spnego OkAsDelegate true false true false false false
- * @run main/othervm -Dtest.spnego OkAsDelegate true true false true false true
- * @run main/othervm -Dtest.spnego OkAsDelegate true true true true false true
- * @run main/othervm -Dtest.spnego -Dtest.kdc.policy.ok-as-delegate OkAsDelegate true false true true true true
- * @run main/othervm -Dtest.spnego -Dtest.kdc.policy.ok-as-delegate OkAsDelegate true true true true true true
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock -Dtest.spnego OkAsDelegate false true true false false false
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock -Dtest.spnego OkAsDelegate true false false false false false
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock -Dtest.spnego OkAsDelegate true false true false false false
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock -Dtest.spnego OkAsDelegate true true false true false true
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock -Dtest.spnego OkAsDelegate true true true true false true
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock -Dtest.spnego -Dtest.kdc.policy.ok-as-delegate OkAsDelegate true false true true true true
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock -Dtest.spnego -Dtest.kdc.policy.ok-as-delegate OkAsDelegate true true true true true true
  * @summary Support OK-AS-DELEGATE flag
  */
 import com.sun.security.jgss.ExtendedGSSContext;
diff --git a/jdk/test/sun/security/krb5/auto/OkAsDelegateXRealm.java b/jdk/test/sun/security/krb5/auto/OkAsDelegateXRealm.java
index 4607619..7d91762 100644
--- a/jdk/test/sun/security/krb5/auto/OkAsDelegateXRealm.java
+++ b/jdk/test/sun/security/krb5/auto/OkAsDelegateXRealm.java
@@ -24,13 +24,13 @@
 /*
  * @test
  * @bug 6853328 7172701
- * @run main/othervm OkAsDelegateXRealm false
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock OkAsDelegateXRealm false
  *      KDC no OK-AS-DELEGATE, fail
- * @run main/othervm -Dtest.kdc.policy.ok-as-delegate OkAsDelegateXRealm true
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock -Dtest.kdc.policy.ok-as-delegate OkAsDelegateXRealm true
  *      KDC set OK-AS-DELEGATE for all, succeed
- * @run main/othervm -Dtest.kdc.policy.ok-as-delegate=host/host.r3.local OkAsDelegateXRealm false
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock -Dtest.kdc.policy.ok-as-delegate=host/host.r3.local OkAsDelegateXRealm false
  *      KDC set OK-AS-DELEGATE for host/host.r3.local only, fail
- * @run main/othervm -Dtest.kdc.policy.ok-as-delegate=host/host.r3.local,krbtgt/R2,krbtgt/R3 OkAsDelegateXRealm true
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock -Dtest.kdc.policy.ok-as-delegate=host/host.r3.local,krbtgt/R2,krbtgt/R3 OkAsDelegateXRealm true
  *      KDC set OK-AS-DELEGATE for all three, succeed
  * @summary Support OK-AS-DELEGATE flag
  */
diff --git a/jdk/test/sun/security/krb5/auto/OnlyDesLogin.java b/jdk/test/sun/security/krb5/auto/OnlyDesLogin.java
index c4b03d1..455a837 100644
--- a/jdk/test/sun/security/krb5/auto/OnlyDesLogin.java
+++ b/jdk/test/sun/security/krb5/auto/OnlyDesLogin.java
@@ -26,7 +26,7 @@
  * @bug 8014310
  * @summary JAAS/Krb5LoginModule using des encytypes failure with NPE after JDK-8012679
  * @compile -XDignore.symbol.file OnlyDesLogin.java
- * @run main/othervm OnlyDesLogin
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock OnlyDesLogin
  */
 
 import sun.security.krb5.Config;
diff --git a/jdk/test/sun/security/krb5/auto/PrincipalNameEquals.java b/jdk/test/sun/security/krb5/auto/PrincipalNameEquals.java
index c4ae6b9..08d6ad8 100644
--- a/jdk/test/sun/security/krb5/auto/PrincipalNameEquals.java
+++ b/jdk/test/sun/security/krb5/auto/PrincipalNameEquals.java
@@ -26,7 +26,7 @@
  * @bug 7061379
  * @summary [Kerberos] Cross-realm authentication fails, due to nameType problem
  * @compile -XDignore.symbol.file PrincipalNameEquals.java
- * @run main/othervm PrincipalNameEquals
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock PrincipalNameEquals
  */
 
 import sun.security.jgss.GSSUtil;
diff --git a/jdk/test/sun/security/krb5/auto/RRC.java b/jdk/test/sun/security/krb5/auto/RRC.java
index ade12a4..3572bbc 100644
--- a/jdk/test/sun/security/krb5/auto/RRC.java
+++ b/jdk/test/sun/security/krb5/auto/RRC.java
@@ -26,7 +26,7 @@
  * @bug 7077640
  * @summary gss wrap for cfx doesn't handle rrc != 0
  * @compile -XDignore.symbol.file RRC.java
- * @run main/othervm RRC
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock RRC
  */
 
 import java.util.Arrays;
diff --git a/jdk/test/sun/security/krb5/auto/RefreshKrb5Config.java b/jdk/test/sun/security/krb5/auto/RefreshKrb5Config.java
index c32258f..9699a27 100644
--- a/jdk/test/sun/security/krb5/auto/RefreshKrb5Config.java
+++ b/jdk/test/sun/security/krb5/auto/RefreshKrb5Config.java
@@ -34,7 +34,7 @@
  * @bug 4745056 8075297
  * @summary Checks if refreshKrb5Config is set to true for Krb5LoginModule,
  *          then configuration will be refreshed before login() method is called
- * @run main/othervm RefreshKrb5Config
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock RefreshKrb5Config
  */
 public class RefreshKrb5Config {
 
diff --git a/jdk/test/sun/security/krb5/auto/ReplayCacheTest.java b/jdk/test/sun/security/krb5/auto/ReplayCacheTest.java
index 79a4da7..6c81c02 100644
--- a/jdk/test/sun/security/krb5/auto/ReplayCacheTest.java
+++ b/jdk/test/sun/security/krb5/auto/ReplayCacheTest.java
@@ -24,8 +24,8 @@
 /*
  * @test
  * @bug 7118809 8001326
- * @run main/othervm ReplayCacheTest jvm
- * @run main/othervm ReplayCacheTest dfl
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock ReplayCacheTest jvm
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock ReplayCacheTest dfl
  * @summary rcache deadlock
  */
 
diff --git a/jdk/test/sun/security/krb5/auto/ReplayCacheTestProc.java b/jdk/test/sun/security/krb5/auto/ReplayCacheTestProc.java
index 25d6854..6413e15 100644
--- a/jdk/test/sun/security/krb5/auto/ReplayCacheTestProc.java
+++ b/jdk/test/sun/security/krb5/auto/ReplayCacheTestProc.java
@@ -27,7 +27,7 @@
  * @summary More krb5 tests
  * @library ../../../../java/security/testlibrary/
  * @compile -XDignore.symbol.file ReplayCacheTestProc.java
- * @run main/othervm/timeout=100 ReplayCacheTestProc
+ * @run main/othervm/timeout=100 -Dsun.net.spi.nameservice.provider.1=ns,mock ReplayCacheTestProc
  */
 
 import java.io.*;
@@ -277,6 +277,7 @@
                 .prop("sun.security.jgss.native", "true")
                 .prop("javax.security.auth.useSubjectCredsOnly", "false")
                 .prop("sun.security.nativegss.debug", "true")
+                .prop("sun.net.spi.nameservice.provider.1", "ns,mock")
                 .debug("N"+i)
                 .start();
     }
@@ -287,6 +288,7 @@
                 .args("S"+i)
                 .prop("sun.security.krb5.rcache", "dfl")
                 .prop("java.io.tmpdir", cwd)
+                .prop("sun.net.spi.nameservice.provider.1", "ns,mock")
                 .start();
     }
     // generates hash of authenticator inside ap-req inside initsectoken
diff --git a/jdk/test/sun/security/krb5/auto/S4U2proxy.java b/jdk/test/sun/security/krb5/auto/S4U2proxy.java
index 10e5652..cd7a3cd 100644
--- a/jdk/test/sun/security/krb5/auto/S4U2proxy.java
+++ b/jdk/test/sun/security/krb5/auto/S4U2proxy.java
@@ -26,8 +26,8 @@
  * @bug 6355584 8044215
  * @summary Introduce constrained Kerberos delegation
  * @compile -XDignore.symbol.file S4U2proxy.java
- * @run main/othervm S4U2proxy krb5
- * @run main/othervm S4U2proxy spnego
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock S4U2proxy krb5
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock S4U2proxy spnego
  */
 
 import java.util.Arrays;
diff --git a/jdk/test/sun/security/krb5/auto/S4U2proxyGSS.java b/jdk/test/sun/security/krb5/auto/S4U2proxyGSS.java
index f2f0b30..d0006b6 100644
--- a/jdk/test/sun/security/krb5/auto/S4U2proxyGSS.java
+++ b/jdk/test/sun/security/krb5/auto/S4U2proxyGSS.java
@@ -26,8 +26,8 @@
  * @bug 6355584
  * @summary Introduce constrained Kerberos delegation
  * @compile -XDignore.symbol.file S4U2proxyGSS.java
- * @run main/othervm -Djavax.security.auth.useSubjectCredsOnly=false S4U2proxyGSS krb5
- * @run main/othervm -Djavax.security.auth.useSubjectCredsOnly=false S4U2proxyGSS spnego
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock -Djavax.security.auth.useSubjectCredsOnly=false S4U2proxyGSS krb5
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock -Djavax.security.auth.useSubjectCredsOnly=false S4U2proxyGSS spnego
  */
 
 import java.io.File;
diff --git a/jdk/test/sun/security/krb5/auto/S4U2self.java b/jdk/test/sun/security/krb5/auto/S4U2self.java
index a6c4b21..bfbf0dc 100644
--- a/jdk/test/sun/security/krb5/auto/S4U2self.java
+++ b/jdk/test/sun/security/krb5/auto/S4U2self.java
@@ -26,13 +26,13 @@
  * @bug 6355584
  * @summary Introduce constrained Kerberos delegation
  * @compile -XDignore.symbol.file S4U2self.java
- * @run main/othervm -Dsun.security.krb5.debug=false S4U2self krb5 0
- * @run main/othervm/fail -Dsun.security.krb5.debug=false S4U2self krb5 1
- * @run main/othervm/fail -Dsun.security.krb5.debug=false S4U2self krb5 2
- * @run main/othervm/fail -Dsun.security.krb5.debug=false S4U2self krb5 3
- * @run main/othervm/fail -Dsun.security.krb5.debug=false S4U2self krb5 4
- * @run main/othervm/fail -Dsun.security.krb5.debug=false S4U2self krb5 5
- * @run main/othervm -Dsun.security.krb5.debug=false S4U2self spnego
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock -Dsun.security.krb5.debug=false S4U2self krb5 0
+ * @run main/othervm/fail -Dsun.net.spi.nameservice.provider.1=ns,mock -Dsun.security.krb5.debug=false S4U2self krb5 1
+ * @run main/othervm/fail -Dsun.net.spi.nameservice.provider.1=ns,mock -Dsun.security.krb5.debug=false S4U2self krb5 2
+ * @run main/othervm/fail -Dsun.net.spi.nameservice.provider.1=ns,mock -Dsun.security.krb5.debug=false S4U2self krb5 3
+ * @run main/othervm/fail -Dsun.net.spi.nameservice.provider.1=ns,mock -Dsun.security.krb5.debug=false S4U2self krb5 4
+ * @run main/othervm/fail -Dsun.net.spi.nameservice.provider.1=ns,mock -Dsun.security.krb5.debug=false S4U2self krb5 5
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock -Dsun.security.krb5.debug=false S4U2self spnego
  */
 
 import java.util.Arrays;
diff --git a/jdk/test/sun/security/krb5/auto/S4U2selfAsServer.java b/jdk/test/sun/security/krb5/auto/S4U2selfAsServer.java
index 467129c..33c3117 100644
--- a/jdk/test/sun/security/krb5/auto/S4U2selfAsServer.java
+++ b/jdk/test/sun/security/krb5/auto/S4U2selfAsServer.java
@@ -26,8 +26,8 @@
  * @bug 6355584
  * @summary Introduce constrained Kerberos delegation
  * @compile -XDignore.symbol.file S4U2selfAsServer.java
- * @run main/othervm S4U2selfAsServer krb5
- * @run main/othervm S4U2selfAsServer spnego
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock S4U2selfAsServer krb5
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock S4U2selfAsServer spnego
  */
 
 import java.util.Arrays;
diff --git a/jdk/test/sun/security/krb5/auto/S4U2selfAsServerGSS.java b/jdk/test/sun/security/krb5/auto/S4U2selfAsServerGSS.java
index 0ff2b7b..47e52ab 100644
--- a/jdk/test/sun/security/krb5/auto/S4U2selfAsServerGSS.java
+++ b/jdk/test/sun/security/krb5/auto/S4U2selfAsServerGSS.java
@@ -26,8 +26,8 @@
  * @bug 6355584
  * @summary Introduce constrained Kerberos delegation
  * @compile -XDignore.symbol.file S4U2selfAsServerGSS.java
- * @run main/othervm -Djavax.security.auth.useSubjectCredsOnly=false S4U2selfAsServerGSS krb5
- * @run main/othervm -Djavax.security.auth.useSubjectCredsOnly=false S4U2selfAsServerGSS spnego
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock -Djavax.security.auth.useSubjectCredsOnly=false S4U2selfAsServerGSS krb5
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock -Djavax.security.auth.useSubjectCredsOnly=false S4U2selfAsServerGSS spnego
  */
 
 import java.io.File;
diff --git a/jdk/test/sun/security/krb5/auto/S4U2selfGSS.java b/jdk/test/sun/security/krb5/auto/S4U2selfGSS.java
index f060c78..40c93fc 100644
--- a/jdk/test/sun/security/krb5/auto/S4U2selfGSS.java
+++ b/jdk/test/sun/security/krb5/auto/S4U2selfGSS.java
@@ -26,8 +26,8 @@
  * @bug 6355584
  * @summary Introduce constrained Kerberos delegation
  * @compile -XDignore.symbol.file S4U2selfGSS.java
- * @run main/othervm -Dsun.security.krb5.debug=false S4U2selfGSS krb5
- * @run main/othervm -Dsun.security.krb5.debug=false S4U2selfGSS spnego
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock -Dsun.security.krb5.debug=false S4U2selfGSS krb5
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock -Dsun.security.krb5.debug=false S4U2selfGSS spnego
  */
 
 import java.util.Arrays;
diff --git a/jdk/test/sun/security/krb5/auto/SPNEGO.java b/jdk/test/sun/security/krb5/auto/SPNEGO.java
index 250a942..85ff5aa 100644
--- a/jdk/test/sun/security/krb5/auto/SPNEGO.java
+++ b/jdk/test/sun/security/krb5/auto/SPNEGO.java
@@ -26,7 +26,7 @@
  * @bug 7040151
  * @summary SPNEGO GSS code does not parse tokens in accordance to RFC 2478
  * @compile -XDignore.symbol.file SPNEGO.java
- * @run main/othervm SPNEGO
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock SPNEGO
  */
 
 import sun.security.jgss.GSSUtil;
diff --git a/jdk/test/sun/security/krb5/auto/SSL.java b/jdk/test/sun/security/krb5/auto/SSL.java
index 5605df1..5d6bdb9 100644
--- a/jdk/test/sun/security/krb5/auto/SSL.java
+++ b/jdk/test/sun/security/krb5/auto/SSL.java
@@ -26,17 +26,17 @@
  * @bug 6894643 6913636 8005523 8025123
  * @summary Test JSSE Kerberos ciphersuite
 
- * @run main/othervm SSL TLS_KRB5_WITH_RC4_128_SHA
- * @run main/othervm SSL TLS_KRB5_WITH_RC4_128_SHA unbound
- * @run main/othervm SSL TLS_KRB5_WITH_RC4_128_SHA unbound sni
- * @run main/othervm SSL TLS_KRB5_WITH_3DES_EDE_CBC_SHA
- * @run main/othervm SSL TLS_KRB5_WITH_3DES_EDE_CBC_MD5
- * @run main/othervm SSL TLS_KRB5_WITH_DES_CBC_SHA
- * @run main/othervm SSL TLS_KRB5_WITH_DES_CBC_MD5
- * @run main/othervm SSL TLS_KRB5_EXPORT_WITH_RC4_40_SHA
- * @run main/othervm SSL TLS_KRB5_EXPORT_WITH_RC4_40_MD5
- * @run main/othervm SSL TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA
- * @run main/othervm SSL TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock SSL TLS_KRB5_WITH_RC4_128_SHA
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock SSL TLS_KRB5_WITH_RC4_128_SHA unbound
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock SSL TLS_KRB5_WITH_RC4_128_SHA unbound sni
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock SSL TLS_KRB5_WITH_3DES_EDE_CBC_SHA
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock SSL TLS_KRB5_WITH_3DES_EDE_CBC_MD5
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock SSL TLS_KRB5_WITH_DES_CBC_SHA
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock SSL TLS_KRB5_WITH_DES_CBC_MD5
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock SSL TLS_KRB5_EXPORT_WITH_RC4_40_SHA
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock SSL TLS_KRB5_EXPORT_WITH_RC4_40_MD5
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock SSL TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock SSL TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5
  */
 import java.io.*;
 import java.security.Permission;
diff --git a/jdk/test/sun/security/krb5/auto/SaslBasic.java b/jdk/test/sun/security/krb5/auto/SaslBasic.java
index ef38ab3..175e4b4 100644
--- a/jdk/test/sun/security/krb5/auto/SaslBasic.java
+++ b/jdk/test/sun/security/krb5/auto/SaslBasic.java
@@ -26,8 +26,8 @@
  * @bug 7110803
  * @summary SASL service for multiple hostnames
  * @compile -XDignore.symbol.file SaslBasic.java
- * @run main/othervm SaslBasic bound
- * @run main/othervm SaslBasic unbound
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock SaslBasic bound
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock SaslBasic unbound
  */
 import java.io.IOException;
 import java.util.Arrays;
diff --git a/jdk/test/sun/security/krb5/auto/SaslGSS.java b/jdk/test/sun/security/krb5/auto/SaslGSS.java
index ec54193..d21cfeb 100644
--- a/jdk/test/sun/security/krb5/auto/SaslGSS.java
+++ b/jdk/test/sun/security/krb5/auto/SaslGSS.java
@@ -27,7 +27,7 @@
  * @summary SASL: auth-conf negotiated, but unencrypted data is accepted,
   *         reset to unencrypt
  * @compile -XDignore.symbol.file SaslGSS.java
- * @run main/othervm SaslGSS
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock SaslGSS
  */
 
 import javax.security.auth.callback.Callback;
diff --git a/jdk/test/sun/security/krb5/auto/SaslUnbound.java b/jdk/test/sun/security/krb5/auto/SaslUnbound.java
index 797d66b..32dc9d3 100644
--- a/jdk/test/sun/security/krb5/auto/SaslUnbound.java
+++ b/jdk/test/sun/security/krb5/auto/SaslUnbound.java
@@ -26,11 +26,11 @@
  * @bug 8001104
  * @summary Unbound SASL service: the GSSAPI/krb5 mech
  * @compile -XDignore.symbol.file SaslUnbound.java
- * @run main/othervm SaslUnbound 0
- * @run main/othervm/fail SaslUnbound 1
- * @run main/othervm/fail SaslUnbound 2
- * @run main/othervm/fail SaslUnbound 3
- * @run main/othervm/fail SaslUnbound 4
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock SaslUnbound 0
+ * @run main/othervm/fail -Dsun.net.spi.nameservice.provider.1=ns,mock SaslUnbound 1
+ * @run main/othervm/fail -Dsun.net.spi.nameservice.provider.1=ns,mock SaslUnbound 2
+ * @run main/othervm/fail -Dsun.net.spi.nameservice.provider.1=ns,mock SaslUnbound 3
+ * @run main/othervm/fail -Dsun.net.spi.nameservice.provider.1=ns,mock SaslUnbound 4
  */
 import java.io.IOException;
 import java.util.Arrays;
diff --git a/jdk/test/sun/security/krb5/auto/SpnegoLifeTime.java b/jdk/test/sun/security/krb5/auto/SpnegoLifeTime.java
index 906cfbe..554956a 100644
--- a/jdk/test/sun/security/krb5/auto/SpnegoLifeTime.java
+++ b/jdk/test/sun/security/krb5/auto/SpnegoLifeTime.java
@@ -26,7 +26,7 @@
  * @bug 8000653
  * @summary SPNEGO tests fail at context.getDelegCred().getRemainingInitLifetime(mechOid)
  * @compile -XDignore.symbol.file SpnegoLifeTime.java
- * @run main/othervm SpnegoLifeTime
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock SpnegoLifeTime
  */
 
 import org.ietf.jgss.Oid;
diff --git a/jdk/test/sun/security/krb5/auto/SpnegoReqFlags.java b/jdk/test/sun/security/krb5/auto/SpnegoReqFlags.java
index 62c5504..778fab9 100644
--- a/jdk/test/sun/security/krb5/auto/SpnegoReqFlags.java
+++ b/jdk/test/sun/security/krb5/auto/SpnegoReqFlags.java
@@ -24,7 +24,7 @@
 /*
  * @test
  * @bug 6815182
- * @run main/othervm SpnegoReqFlags
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock SpnegoReqFlags
  * @summary GSSAPI/SPNEGO does not work with server using MIT Kerberos library
  */
 
diff --git a/jdk/test/sun/security/krb5/auto/TcpTimeout.java b/jdk/test/sun/security/krb5/auto/TcpTimeout.java
index 45699fb..14cacc9 100644
--- a/jdk/test/sun/security/krb5/auto/TcpTimeout.java
+++ b/jdk/test/sun/security/krb5/auto/TcpTimeout.java
@@ -25,7 +25,7 @@
  * @test
  * @bug 6952519
  * @compile -XDignore.symbol.file TcpTimeout.java
- * @run main/othervm TcpTimeout
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock TcpTimeout
  * @summary kdc_timeout is not being honoured when using TCP
  */
 
diff --git a/jdk/test/sun/security/krb5/auto/Test5653.java b/jdk/test/sun/security/krb5/auto/Test5653.java
index 4384b87..afa0e97 100644
--- a/jdk/test/sun/security/krb5/auto/Test5653.java
+++ b/jdk/test/sun/security/krb5/auto/Test5653.java
@@ -24,7 +24,7 @@
 /*
  * @test
  * @bug 6895424
- * @run main/othervm Test5653
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock Test5653
  * @summary RFC 5653
  */
 
diff --git a/jdk/test/sun/security/krb5/auto/TicketSName.java b/jdk/test/sun/security/krb5/auto/TicketSName.java
index 458d478..6e11efc 100644
--- a/jdk/test/sun/security/krb5/auto/TicketSName.java
+++ b/jdk/test/sun/security/krb5/auto/TicketSName.java
@@ -26,7 +26,7 @@
  * @bug 8178794
  * @summary krb5 client should ignore sname in incoming tickets
  * @compile -XDignore.symbol.file TicketSName.java
- * @run main/othervm -Dtest.kdc.diff.sname TicketSName
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock -Dtest.kdc.diff.sname TicketSName
  */
 
 import sun.security.jgss.GSSUtil;
diff --git a/jdk/test/sun/security/krb5/auto/TwoOrThree.java b/jdk/test/sun/security/krb5/auto/TwoOrThree.java
index 5af545b..e990417 100644
--- a/jdk/test/sun/security/krb5/auto/TwoOrThree.java
+++ b/jdk/test/sun/security/krb5/auto/TwoOrThree.java
@@ -26,11 +26,11 @@
  * @bug 8005447
  * @summary default principal can act as anyone
  * @compile -XDignore.symbol.file TwoOrThree.java
- * @run main/othervm TwoOrThree first first
- * @run main/othervm/fail TwoOrThree first second
- * @run main/othervm TwoOrThree - first
- * @run main/othervm TwoOrThree - second
- * @run main/othervm/fail TwoOrThree - third
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock TwoOrThree first first
+ * @run main/othervm/fail -Dsun.net.spi.nameservice.provider.1=ns,mock TwoOrThree first second
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock TwoOrThree - first
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock TwoOrThree - second
+ * @run main/othervm/fail -Dsun.net.spi.nameservice.provider.1=ns,mock TwoOrThree - third
  */
 
 import java.nio.file.Files;
diff --git a/jdk/test/sun/security/krb5/auto/TwoPrinces.java b/jdk/test/sun/security/krb5/auto/TwoPrinces.java
index 30f16e9..13fe41a 100644
--- a/jdk/test/sun/security/krb5/auto/TwoPrinces.java
+++ b/jdk/test/sun/security/krb5/auto/TwoPrinces.java
@@ -25,7 +25,7 @@
  * @test
  * @bug 6894072
  * @compile -XDignore.symbol.file TwoPrinces.java
- * @run main/othervm TwoPrinces
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock TwoPrinces
  * @summary always refresh keytab
  */
 
diff --git a/jdk/test/sun/security/krb5/auto/TwoTab.java b/jdk/test/sun/security/krb5/auto/TwoTab.java
index dd2cf96..6c88d9e 100644
--- a/jdk/test/sun/security/krb5/auto/TwoTab.java
+++ b/jdk/test/sun/security/krb5/auto/TwoTab.java
@@ -26,7 +26,7 @@
  * @bug 7152176
  * @summary More krb5 tests
  * @compile -XDignore.symbol.file TwoTab.java
- * @run main/othervm TwoTab
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock TwoTab
  */
 
 import java.io.File;
diff --git a/jdk/test/sun/security/krb5/auto/UdpTcp.java b/jdk/test/sun/security/krb5/auto/UdpTcp.java
index ae54b79..a8d4f23 100644
--- a/jdk/test/sun/security/krb5/auto/UdpTcp.java
+++ b/jdk/test/sun/security/krb5/auto/UdpTcp.java
@@ -24,8 +24,8 @@
 /*
  * @test
  * @bug 4966382 8039132
- * @run main/othervm UdpTcp UDP
- * @run main/othervm UdpTcp TCP
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock UdpTcp UDP
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock UdpTcp TCP
  * @summary udp or tcp
  */
 
diff --git a/jdk/test/sun/security/krb5/auto/UnboundSSL.java b/jdk/test/sun/security/krb5/auto/UnboundSSL.java
index 8ff73aad8..063729b 100644
--- a/jdk/test/sun/security/krb5/auto/UnboundSSL.java
+++ b/jdk/test/sun/security/krb5/auto/UnboundSSL.java
@@ -34,9 +34,9 @@
  * @bug 8025123
  * @summary Checks if an unbound server can handle connections
  *          only for allowed service principals
- * @run main/othervm/java.security.policy=unbound.ssl.policy UnboundSSL
+ * @run main/othervm/java.security.policy=unbound.ssl.policy -Dsun.net.spi.nameservice.provider.1=ns,mock UnboundSSL
  *                              unbound.ssl.jaas.conf server_star
- * @run main/othervm/java.security.policy=unbound.ssl.policy UnboundSSL
+ * @run main/othervm/java.security.policy=unbound.ssl.policy -Dsun.net.spi.nameservice.provider.1=ns,mock UnboundSSL
  *                              unbound.ssl.jaas.conf server_multiple_principals
  */
 public class UnboundSSL {
diff --git a/jdk/test/sun/security/krb5/auto/UnboundSSLMultipleKeys.java b/jdk/test/sun/security/krb5/auto/UnboundSSLMultipleKeys.java
index aa1ea2b3..a3c209d 100644
--- a/jdk/test/sun/security/krb5/auto/UnboundSSLMultipleKeys.java
+++ b/jdk/test/sun/security/krb5/auto/UnboundSSLMultipleKeys.java
@@ -33,9 +33,9 @@
  * @test
  * @bug 8025123
  * @summary Checks if an unbound server pick up a correct key from keytab
- * @run main/othervm UnboundSSLMultipleKeys
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock UnboundSSLMultipleKeys
  *                              unbound.ssl.jaas.conf server_star
- * @run main/othervm UnboundSSLMultipleKeys
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock UnboundSSLMultipleKeys
  *                              unbound.ssl.jaas.conf server_multiple_principals
  */
 public class UnboundSSLMultipleKeys {
diff --git a/jdk/test/sun/security/krb5/auto/UnboundSSLPrincipalProperty.java b/jdk/test/sun/security/krb5/auto/UnboundSSLPrincipalProperty.java
index ab8549e..9f78493 100644
--- a/jdk/test/sun/security/krb5/auto/UnboundSSLPrincipalProperty.java
+++ b/jdk/test/sun/security/krb5/auto/UnboundSSLPrincipalProperty.java
@@ -33,9 +33,9 @@
  * @bug 8025123
  * @summary Checks if an unbound server uses a service principal
  *          from sun.security.krb5.principal system property if specified
- * @run main/othervm UnboundSSLPrincipalProperty
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock UnboundSSLPrincipalProperty
  *                              unbound.ssl.jaas.conf server_star
- * @run main/othervm UnboundSSLPrincipalProperty
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock UnboundSSLPrincipalProperty
  *                              unbound.ssl.jaas.conf server_multiple_principals
  */
 public class UnboundSSLPrincipalProperty {
diff --git a/jdk/test/sun/security/krb5/auto/UnboundService.java b/jdk/test/sun/security/krb5/auto/UnboundService.java
index 1327f78..a15335e 100644
--- a/jdk/test/sun/security/krb5/auto/UnboundService.java
+++ b/jdk/test/sun/security/krb5/auto/UnboundService.java
@@ -26,14 +26,14 @@
  * @bug 8001104
  * @summary Unbound SASL service: the GSSAPI/krb5 mech
  * @compile -XDignore.symbol.file UnboundService.java
- * @run main/othervm UnboundService null null
- * @run main/othervm UnboundService server/host.rabbit.hole null
- * @run main/othervm UnboundService server/host.rabbit.hole@RABBIT.HOLE null
- * @run main/othervm/fail UnboundService backend/host.rabbit.hole null
- * @run main/othervm UnboundService null server@host.rabbit.hole
- * @run main/othervm UnboundService server/host.rabbit.hole server@host.rabbit.hole
- * @run main/othervm UnboundService server/host.rabbit.hole@RABBIT.HOLE server@host.rabbit.hole
- * @run main/othervm/fail UnboundService backend/host.rabbit.hole server@host.rabbit.hole
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock UnboundService null null
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock UnboundService server/host.rabbit.hole null
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock UnboundService server/host.rabbit.hole@RABBIT.HOLE null
+ * @run main/othervm/fail -Dsun.net.spi.nameservice.provider.1=ns,mock UnboundService backend/host.rabbit.hole null
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock UnboundService null server@host.rabbit.hole
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock UnboundService server/host.rabbit.hole server@host.rabbit.hole
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock UnboundService server/host.rabbit.hole@RABBIT.HOLE server@host.rabbit.hole
+ * @run main/othervm/fail -Dsun.net.spi.nameservice.provider.1=ns,mock UnboundService backend/host.rabbit.hole server@host.rabbit.hole
  */
 
 import java.io.File;
diff --git a/jdk/test/sun/security/krb5/auto/UseCacheAndStoreKey.java b/jdk/test/sun/security/krb5/auto/UseCacheAndStoreKey.java
index 3769643..82f9435 100644
--- a/jdk/test/sun/security/krb5/auto/UseCacheAndStoreKey.java
+++ b/jdk/test/sun/security/krb5/auto/UseCacheAndStoreKey.java
@@ -27,7 +27,7 @@
  * @summary Krb5LoginModule shows NPE when both useTicketCache and storeKey
  *          are set to true
  * @compile -XDignore.symbol.file UseCacheAndStoreKey.java
- * @run main/othervm UseCacheAndStoreKey
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock UseCacheAndStoreKey
  */
 
 import java.io.FileOutputStream;
diff --git a/jdk/test/sun/security/krb5/auto/W83.java b/jdk/test/sun/security/krb5/auto/W83.java
index dea4e76..9b30db7 100644
--- a/jdk/test/sun/security/krb5/auto/W83.java
+++ b/jdk/test/sun/security/krb5/auto/W83.java
@@ -26,8 +26,8 @@
  * @bug 6932525 6951366 6959292
  * @summary kerberos login failure on win2008 with AD set to win2000 compat mode
  * and cannot login if session key and preauth does not use the same etype
- * @run main/othervm -D6932525 W83
- * @run main/othervm -D6959292 W83
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock -D6932525 W83
+ * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock -D6959292 W83
  */
 import com.sun.security.auth.module.Krb5LoginModule;
 import java.io.File;
diff --git a/jdk/test/sun/security/ssl/SSLSocketImpl/SSLSocketCloseHang.java b/jdk/test/sun/security/ssl/SSLSocketImpl/SSLSocketCloseHang.java
index 6848e13..b7bde00 100644
--- a/jdk/test/sun/security/ssl/SSLSocketImpl/SSLSocketCloseHang.java
+++ b/jdk/test/sun/security/ssl/SSLSocketImpl/SSLSocketCloseHang.java
@@ -100,8 +100,11 @@
          */
         serverReady = true;
 
+        System.err.println("Server accepting: " + System.nanoTime());
         SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept();
+        System.err.println("Server accepted: " + System.nanoTime());
         sslSocket.startHandshake();
+        System.err.println("Server handshake complete: " + System.nanoTime());
         while (!clientClosed) {
             Thread.sleep(500);
         }
@@ -123,10 +126,11 @@
         while (!serverReady) {
             Thread.sleep(50);
         }
+        Thread.sleep(500);
         System.out.println("server ready");
 
         Socket baseSocket = new Socket("localhost", serverPort);
-        baseSocket.setSoTimeout(100);
+        baseSocket.setSoTimeout(1000);
 
         SSLSocketFactory sslsf =
             (SSLSocketFactory) SSLSocketFactory.getDefault();
@@ -134,15 +138,16 @@
             sslsf.createSocket(baseSocket, "localhost", serverPort, false);
 
         // handshaking
+        System.err.println("Client starting handshake: " + System.nanoTime());
         sslSocket.startHandshake();
-        System.out.println("handshake done");
+        System.err.println("Client handshake done: " + System.nanoTime());
 
         Thread.sleep(500);
-        System.out.println("client closing");
+        System.err.println("Client closing: " + System.nanoTime());
 
         sslSocket.close();
         clientClosed = true;
-        System.out.println("client closed");
+        System.err.println("Client closed: " + System.nanoTime());
     }
 
     /*
diff --git a/jdk/test/sun/security/tools/keytool/RealType.java b/jdk/test/sun/security/tools/keytool/RealType.java
new file mode 100644
index 0000000..6c6cdcb
--- /dev/null
+++ b/jdk/test/sun/security/tools/keytool/RealType.java
@@ -0,0 +1,61 @@
+/*
+ * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8192987
+ * @summary keytool should remember real storetype if it is not provided
+ * @library /lib/testlibrary
+ * @run main/othervm RealType
+ */
+
+import jdk.testlibrary.SecurityTools;
+import jdk.testlibrary.OutputAnalyzer;
+
+import java.nio.file.Files;
+import java.nio.file.Paths;
+
+public class RealType {
+
+    public static void main(String[] args) throws Throwable {
+
+        kt("-genkeypair -alias a -dname CN=A -keypass changeit -storetype jks")
+                .shouldHaveExitValue(0);
+
+        // -keypasswd command should be allowed on JKS
+        kt("-keypasswd -alias a -new t0ps3cr3t")
+                .shouldHaveExitValue(0);
+
+        Files.delete(Paths.get("ks"));
+
+        kt("-genkeypair -alias a -dname CN=A -keypass changeit -storetype pkcs12")
+                .shouldHaveExitValue(0);
+
+        // A pkcs12 keystore cannot be loaded as a JCEKS keystore
+        kt("-list -storetype jceks").shouldHaveExitValue(1);
+    }
+
+    static OutputAnalyzer kt(String arg) throws Exception {
+        return SecurityTools.keytool("-debug -keystore ks -storepass changeit " + arg);
+    }
+}
diff --git a/langtools/.hgtags b/langtools/.hgtags
index 12404a2..056107a 100644
--- a/langtools/.hgtags
+++ b/langtools/.hgtags
@@ -856,3 +856,9 @@
 4cd77f7e459d629a2e352fc326cb56ce8fbf55bb jdk8u171-b02
 a459065c13afe9e0e122fa232f48ba95ab23d3f5 jdk8u171-b03
 c25be482f93d465d7a1fadf1df1428683d1b42fb jdk8u171-b04
+206179228d91783e943a857eec52a12b9985db2a jdk8u171-b05
+53092d863cb60907700ac5fd7d12fc28ce871b2a jdk8u172-b00
+47a91ecb0b875b8c03c335e11bfe5052bad4f1cf jdk8u172-b01
+989188d1a978fea3255e733c89718b8c0b21a231 jdk8u172-b02
+c563af72dd015eb3e528dbd121d23f0743276baa jdk8u172-b03
+2fefa5723300276ed0076e09d491622030105a25 jdk8u172-b04
diff --git a/langtools/src/share/classes/com/sun/tools/javac/comp/LambdaToMethod.java b/langtools/src/share/classes/com/sun/tools/javac/comp/LambdaToMethod.java
index 436ffea..4687ffe 100644
--- a/langtools/src/share/classes/com/sun/tools/javac/comp/LambdaToMethod.java
+++ b/langtools/src/share/classes/com/sun/tools/javac/comp/LambdaToMethod.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2010, 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
@@ -2009,7 +2009,7 @@
                         Assert.error(skind.name());
                         throw new AssertionError();
                 }
-                if (ret != sym) {
+                if (ret != sym && skind.propagateAnnotations()) {
                     ret.setDeclarationAttributes(sym.getRawAttributes());
                     ret.setTypeAttributes(sym.getRawTypeAttributes());
                 }
@@ -2045,7 +2045,6 @@
                             if (m.containsKey(lambdaIdent.sym)) {
                                 Symbol tSym = m.get(lambdaIdent.sym);
                                 JCTree t = make.Ident(tSym).setType(lambdaIdent.type);
-                                tSym.setTypeAttributes(lambdaIdent.sym.getRawTypeAttributes());
                                 return t;
                             }
                             break;
@@ -2054,7 +2053,6 @@
                                 // Transform outer instance variable references anchoring them to the captured synthetic.
                                 Symbol tSym = m.get(lambdaIdent.sym.owner);
                                 JCExpression t = make.Ident(tSym).setType(lambdaIdent.sym.owner.type);
-                                tSym.setTypeAttributes(lambdaIdent.sym.owner.getRawTypeAttributes());
                                 t = make.Select(t, lambdaIdent.name);
                                 t.setType(lambdaIdent.type);
                                 TreeInfo.setSymbol(t, lambdaIdent.sym);
@@ -2075,7 +2073,6 @@
                 if (m.containsKey(fieldAccess.sym.owner)) {
                     Symbol tSym = m.get(fieldAccess.sym.owner);
                     JCExpression t = make.Ident(tSym).setType(fieldAccess.sym.owner.type);
-                    tSym.setTypeAttributes(fieldAccess.sym.owner.getRawTypeAttributes());
                     return t;
                 }
                 return null;
@@ -2272,6 +2269,17 @@
         CAPTURED_THIS,  // class symbols to translated synthetic parameters (for captured member access)
         CAPTURED_OUTER_THIS, // used when `this' capture is illegal, but outer this capture is legit (JDK-8129740)
         TYPE_VAR;       // original to translated lambda type variables
+
+        boolean propagateAnnotations() {
+            switch (this) {
+                case CAPTURED_VAR:
+                case CAPTURED_THIS:
+                case CAPTURED_OUTER_THIS:
+                    return false;
+                default:
+                    return true;
+           }
+        }
     }
 
     /**
diff --git a/langtools/test/tools/javac/annotations/typeAnnotations/classfile/TypeAnnotationPropagationTest.java b/langtools/test/tools/javac/annotations/typeAnnotations/classfile/TypeAnnotationPropagationTest.java
new file mode 100644
index 0000000..7981133
--- /dev/null
+++ b/langtools/test/tools/javac/annotations/typeAnnotations/classfile/TypeAnnotationPropagationTest.java
@@ -0,0 +1,100 @@
+/*
+ * Copyright (c) 2017, Google Inc. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8144185 8191969
+ * @summary javac produces incorrect RuntimeInvisibleTypeAnnotations length attribute
+ */
+
+import static java.lang.annotation.ElementType.TYPE_USE;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+
+import com.sun.tools.classfile.Attribute;
+import com.sun.tools.classfile.ClassFile;
+import com.sun.tools.classfile.Code_attribute;
+import com.sun.tools.classfile.Method;
+import com.sun.tools.classfile.RuntimeVisibleTypeAnnotations_attribute;
+import com.sun.tools.classfile.TypeAnnotation;
+import java.lang.annotation.Retention;
+import java.lang.annotation.Target;
+import java.util.Arrays;
+import java.util.Objects;
+
+public class TypeAnnotationPropagationTest extends ClassfileTestHelper {
+    public static void main(String[] args) throws Exception {
+        new TypeAnnotationPropagationTest().run();
+    }
+
+    public void run() throws Exception {
+        ClassFile cf = getClassFile("TypeAnnotationPropagationTest$Test.class");
+
+        Method f = null;
+        for (Method m : cf.methods) {
+            if (m.getName(cf.constant_pool).contains("f")) {
+                f = m;
+                break;
+            }
+        }
+
+        int idx = f.attributes.getIndex(cf.constant_pool, Attribute.Code);
+        Code_attribute cattr = (Code_attribute) f.attributes.get(idx);
+        idx = cattr.attributes.getIndex(cf.constant_pool, Attribute.RuntimeVisibleTypeAnnotations);
+        RuntimeVisibleTypeAnnotations_attribute attr =
+                (RuntimeVisibleTypeAnnotations_attribute) cattr.attributes.get(idx);
+
+        TypeAnnotation anno = attr.annotations[0];
+        assertEquals(anno.position.lvarOffset, new int[] {3}, "start_pc");
+        assertEquals(anno.position.lvarLength, new int[] {8}, "length");
+        assertEquals(anno.position.lvarIndex, new int[] {1}, "index");
+    }
+
+    void assertEquals(int[] actual, int[] expected, String message) {
+        if (!Arrays.equals(actual, expected)) {
+            throw new AssertionError(
+                    String.format(
+                            "actual: %s, expected: %s, %s",
+                            Arrays.toString(actual), Arrays.toString(expected), message));
+        }
+    }
+
+    /** ********************* Test class ************************ */
+    static class Test {
+        void f() {
+            @A String s = "";
+            Runnable r =
+                    () -> {
+                        Objects.requireNonNull(s);
+                        Objects.requireNonNull(s);
+                        Objects.requireNonNull(s);
+                        Objects.requireNonNull(s);
+                        Objects.requireNonNull(s);
+                        Objects.requireNonNull(s);
+                    };
+        }
+
+        @Retention(RUNTIME)
+        @Target(TYPE_USE)
+        @interface A {}
+    }
+}
diff --git a/nashorn/.hgtags b/nashorn/.hgtags
index c5c13e2..ef105ea 100644
--- a/nashorn/.hgtags
+++ b/nashorn/.hgtags
@@ -869,3 +869,9 @@
 710e8cf9b7a554469bbaf78e371eb1f4fe086ce2 jdk8u171-b02
 42903e21ee6aaab01763aa04a76378381d0ca58d jdk8u171-b03
 0f09c1423f3454cac9eef7240d2ff831a104b4d8 jdk8u171-b04
+801694cc35e00907f3ef382ae1495e2dadd22278 jdk8u171-b05
+3ae3ebe2e2ee5648c38862179b2b1d1951ad97d7 jdk8u172-b00
+8b311af3f1b260035ff12e86e324f8254b1d760b jdk8u172-b01
+e5e19194a8a2ce6849791bbc2aea2ac1632cdbc2 jdk8u172-b02
+93b6ac37872647ca64877561035f43473da96c04 jdk8u172-b03
+9bd2bd2edbd7c205deafc89c97cb882bce9f232c jdk8u172-b04