Merge
authorasaha
Fri, 12 Jan 2018 15:05:35 -0800
changeset 48590 0d3b030b3eb7
parent 48589 97db4ee6e59a (diff)
parent 48522 c674ff28c69d (current diff)
child 48591 ca245f9f70db
Merge
src/java.compiler/share/classes/javax/lang/model/overview.html
src/java.compiler/share/classes/javax/tools/overview.html
src/jdk.jdeps/share/classes/com/sun/tools/javap/overview.html
test/langtools/tools/javac/T8192885/AddGotoAfterForLoopToLNTTest.java
--- a/src/hotspot/cpu/aarch64/sharedRuntime_aarch64.cpp	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/hotspot/cpu/aarch64/sharedRuntime_aarch64.cpp	Fri Jan 12 15:05:35 2018 -0800
@@ -774,7 +774,7 @@
     __ load_klass(rscratch1, receiver);
     __ ldr(tmp, Address(holder, CompiledICHolder::holder_klass_offset()));
     __ cmp(rscratch1, tmp);
-    __ ldr(rmethod, Address(holder, CompiledICHolder::holder_method_offset()));
+    __ ldr(rmethod, Address(holder, CompiledICHolder::holder_metadata_offset()));
     __ br(Assembler::EQ, ok);
     __ far_jump(RuntimeAddress(SharedRuntime::get_ic_miss_stub()));
 
--- a/src/hotspot/cpu/arm/macroAssembler_arm.cpp	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/hotspot/cpu/arm/macroAssembler_arm.cpp	Fri Jan 12 15:05:35 2018 -0800
@@ -2475,49 +2475,65 @@
 // On success, the result will be in method_result, and execution falls through.
 // On failure, execution transfers to the given label.
 void MacroAssembler::lookup_interface_method(Register Rklass,
-                                             Register Rinterf,
-                                             Register Rindex,
+                                             Register Rintf,
+                                             RegisterOrConstant itable_index,
                                              Register method_result,
-                                             Register temp_reg1,
-                                             Register temp_reg2,
+                                             Register Rscan,
+                                             Register Rtmp,
                                              Label& L_no_such_interface) {
 
-  assert_different_registers(Rklass, Rinterf, temp_reg1, temp_reg2, Rindex);
-
-  Register Ritable = temp_reg1;
+  assert_different_registers(Rklass, Rintf, Rscan, Rtmp);
+
+  const int entry_size = itableOffsetEntry::size() * HeapWordSize;
+  assert(itableOffsetEntry::interface_offset_in_bytes() == 0, "not added for convenience");
 
   // Compute start of first itableOffsetEntry (which is at the end of the vtable)
   const int base = in_bytes(Klass::vtable_start_offset());
   const int scale = exact_log2(vtableEntry::size_in_bytes());
-  ldr_s32(temp_reg2, Address(Rklass, Klass::vtable_length_offset())); // Get length of vtable
-  add(Ritable, Rklass, base);
-  add(Ritable, Ritable, AsmOperand(temp_reg2, lsl, scale));
-
-  Label entry, search;
-
-  b(entry);
-
-  bind(search);
-  add(Ritable, Ritable, itableOffsetEntry::size() * HeapWordSize);
-
-  bind(entry);
-
-  // Check that the entry is non-null.  A null entry means that the receiver
-  // class doesn't implement the interface, and wasn't the same as the
-  // receiver class checked when the interface was resolved.
-
-  ldr(temp_reg2, Address(Ritable, itableOffsetEntry::interface_offset_in_bytes()));
-  cbz(temp_reg2, L_no_such_interface);
-
-  cmp(Rinterf, temp_reg2);
-  b(search, ne);
-
-  ldr_s32(temp_reg2, Address(Ritable, itableOffsetEntry::offset_offset_in_bytes()));
-  add(temp_reg2, temp_reg2, Rklass); // Add offset to Klass*
-  assert(itableMethodEntry::size() * HeapWordSize == wordSize, "adjust the scaling in the code below");
-  assert(itableMethodEntry::method_offset_in_bytes() == 0, "adjust the offset in the code below");
-
-  ldr(method_result, Address::indexed_ptr(temp_reg2, Rindex));
+  ldr_s32(Rtmp, Address(Rklass, Klass::vtable_length_offset())); // Get length of vtable
+  add(Rscan, Rklass, base);
+  add(Rscan, Rscan, AsmOperand(Rtmp, lsl, scale));
+
+  // Search through the itable for an interface equal to incoming Rintf
+  // itable looks like [intface][offset][intface][offset][intface][offset]
+
+  Label loop;
+  bind(loop);
+  ldr(Rtmp, Address(Rscan, entry_size, post_indexed));
+#ifdef AARCH64
+  Label found;
+  cmp(Rtmp, Rintf);
+  b(found, eq);
+  cbnz(Rtmp, loop);
+#else
+  cmp(Rtmp, Rintf);  // set ZF and CF if interface is found
+  cmn(Rtmp, 0, ne);  // check if tmp == 0 and clear CF if it is
+  b(loop, ne);
+#endif // AARCH64
+
+#ifdef AARCH64
+  b(L_no_such_interface);
+  bind(found);
+#else
+  // CF == 0 means we reached the end of itable without finding icklass
+  b(L_no_such_interface, cc);
+#endif // !AARCH64
+
+  if (method_result != noreg) {
+    // Interface found at previous position of Rscan, now load the method
+    ldr_s32(Rtmp, Address(Rscan, itableOffsetEntry::offset_offset_in_bytes() - entry_size));
+    if (itable_index.is_register()) {
+      add(Rtmp, Rtmp, Rklass); // Add offset to Klass*
+      assert(itableMethodEntry::size() * HeapWordSize == wordSize, "adjust the scaling in the code below");
+      assert(itableMethodEntry::method_offset_in_bytes() == 0, "adjust the offset in the code below");
+      ldr(method_result, Address::indexed_ptr(Rtmp, itable_index.as_register()));
+    } else {
+      int method_offset = itableMethodEntry::size() * HeapWordSize * itable_index.as_constant() +
+                          itableMethodEntry::method_offset_in_bytes();
+      add_slow(method_result, Rklass, method_offset);
+      ldr(method_result, Address(method_result, Rtmp));
+    }
+  }
 }
 
 #ifdef COMPILER2
--- a/src/hotspot/cpu/arm/macroAssembler_arm.hpp	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/hotspot/cpu/arm/macroAssembler_arm.hpp	Fri Jan 12 15:05:35 2018 -0800
@@ -1316,7 +1316,7 @@
 
   void lookup_interface_method(Register recv_klass,
                                Register intf_klass,
-                               Register itable_index,
+                               RegisterOrConstant itable_index,
                                Register method_result,
                                Register temp_reg1,
                                Register temp_reg2,
--- a/src/hotspot/cpu/arm/sharedRuntime_arm.cpp	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/hotspot/cpu/arm/sharedRuntime_arm.cpp	Fri Jan 12 15:05:35 2018 -0800
@@ -984,7 +984,7 @@
 
   __ load_klass(receiver_klass, receiver);
   __ ldr(holder_klass, Address(Ricklass, CompiledICHolder::holder_klass_offset()));
-  __ ldr(Rmethod, Address(Ricklass, CompiledICHolder::holder_method_offset()));
+  __ ldr(Rmethod, Address(Ricklass, CompiledICHolder::holder_metadata_offset()));
   __ cmp(receiver_klass, holder_klass);
 
 #ifdef AARCH64
--- a/src/hotspot/cpu/arm/templateTable_arm.cpp	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/hotspot/cpu/arm/templateTable_arm.cpp	Fri Jan 12 15:05:35 2018 -0800
@@ -4198,7 +4198,7 @@
   const Register Rflags  = R3_tmp;
   const Register Rklass  = R3_tmp;
 
-  prepare_invoke(byte_no, Rinterf, Rindex, Rrecv, Rflags);
+  prepare_invoke(byte_no, Rinterf, Rmethod, Rrecv, Rflags);
 
   // Special case of invokeinterface called for virtual method of
   // java.lang.Object.  See cpCacheOop.cpp for details.
@@ -4207,56 +4207,39 @@
   Label notMethod;
   __ tbz(Rflags, ConstantPoolCacheEntry::is_forced_virtual_shift, notMethod);
 
-  __ mov(Rmethod, Rindex);
   invokevirtual_helper(Rmethod, Rrecv, Rflags);
   __ bind(notMethod);
 
   // Get receiver klass into Rklass - also a null check
   __ load_klass(Rklass, Rrecv);
 
+  Label no_such_interface;
+
+  // Receiver subtype check against REFC.
+  __ lookup_interface_method(// inputs: rec. class, interface
+                             Rklass, Rinterf, noreg,
+                             // outputs:  scan temp. reg1, scan temp. reg2
+                             noreg, Ritable, Rtemp,
+                             no_such_interface);
+
   // profile this call
   __ profile_virtual_call(R0_tmp, Rklass);
 
-  // Compute start of first itableOffsetEntry (which is at the end of the vtable)
-  const int base = in_bytes(Klass::vtable_start_offset());
-  assert(vtableEntry::size() == 1, "adjust the scaling in the code below");
-  __ ldr_s32(Rtemp, Address(Rklass, Klass::vtable_length_offset())); // Get length of vtable
-  __ add(Ritable, Rklass, base);
-  __ add(Ritable, Ritable, AsmOperand(Rtemp, lsl, LogBytesPerWord));
-
-  Label entry, search, interface_ok;
-
-  __ b(entry);
-
-  __ bind(search);
-  __ add(Ritable, Ritable, itableOffsetEntry::size() * HeapWordSize);
-
-  __ bind(entry);
-
-  // Check that the entry is non-null.  A null entry means that the receiver
-  // class doesn't implement the interface, and wasn't the same as the
-  // receiver class checked when the interface was resolved.
-
-  __ ldr(Rtemp, Address(Ritable, itableOffsetEntry::interface_offset_in_bytes()));
-  __ cbnz(Rtemp, interface_ok);
-
-  // throw exception
-  __ call_VM(noreg, CAST_FROM_FN_PTR(address,
-                   InterpreterRuntime::throw_IncompatibleClassChangeError));
-
-  // the call_VM checks for exception, so we should never return here.
-  __ should_not_reach_here();
-
-  __ bind(interface_ok);
-
-  __ cmp(Rinterf, Rtemp);
-  __ b(search, ne);
-
-  __ ldr_s32(Rtemp, Address(Ritable, itableOffsetEntry::offset_offset_in_bytes()));
-  __ add(Rtemp, Rtemp, Rklass); // Add offset to Klass*
-  assert(itableMethodEntry::size() == 1, "adjust the scaling in the code below");
-
-  __ ldr(Rmethod, Address::indexed_ptr(Rtemp, Rindex));
+  // Get declaring interface class from method
+  __ ldr(Rtemp, Address(Rmethod, Method::const_offset()));
+  __ ldr(Rtemp, Address(Rtemp, ConstMethod::constants_offset()));
+  __ ldr(Rinterf, Address(Rtemp, ConstantPool::pool_holder_offset_in_bytes()));
+
+  // Get itable index from method
+  __ ldr_s32(Rtemp, Address(Rmethod, Method::itable_index_offset()));
+  __ add(Rtemp, Rtemp, (-Method::itable_index_max)); // small negative constant is too large for an immediate on arm32
+  __ neg(Rindex, Rtemp);
+
+  __ lookup_interface_method(// inputs: rec. class, interface
+                             Rklass, Rinterf, Rindex,
+                             // outputs:  scan temp. reg1, scan temp. reg2
+                             Rmethod, Ritable, Rtemp,
+                             no_such_interface);
 
   // Rmethod: Method* to call
 
@@ -4278,6 +4261,13 @@
 
   // do the call
   __ jump_from_interpreted(Rmethod);
+
+  // throw exception
+  __ bind(no_such_interface);
+  __ restore_method();
+  __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_IncompatibleClassChangeError));
+  // the call_VM checks for exception, so we should never return here.
+  __ should_not_reach_here();
 }
 
 void TemplateTable::invokehandle(int byte_no) {
--- a/src/hotspot/cpu/arm/vtableStubs_arm.cpp	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/hotspot/cpu/arm/vtableStubs_arm.cpp	Fri Jan 12 15:05:35 2018 -0800
@@ -28,6 +28,7 @@
 #include "code/vtableStubs.hpp"
 #include "interp_masm_arm.hpp"
 #include "memory/resourceArea.hpp"
+#include "oops/compiledICHolder.hpp"
 #include "oops/instanceKlass.hpp"
 #include "oops/klassVtable.hpp"
 #include "runtime/sharedRuntime.hpp"
@@ -118,67 +119,48 @@
 
   // R0-R3 / R0-R7 registers hold the arguments and cannot be spoiled
   const Register Rclass  = AARCH64_ONLY(R9)  NOT_AARCH64(R4);
-  const Register Rlength = AARCH64_ONLY(R10)  NOT_AARCH64(R5);
+  const Register Rintf   = AARCH64_ONLY(R10) NOT_AARCH64(R5);
   const Register Rscan   = AARCH64_ONLY(R11) NOT_AARCH64(R6);
-  const Register tmp     = Rtemp;
 
-  assert_different_registers(Ricklass, Rclass, Rlength, Rscan, tmp);
+  assert_different_registers(Ricklass, Rclass, Rintf, Rscan, Rtemp);
 
   // Calculate the start of itable (itable goes after vtable)
   const int scale = exact_log2(vtableEntry::size_in_bytes());
   address npe_addr = __ pc();
   __ load_klass(Rclass, R0);
-  __ ldr_s32(Rlength, Address(Rclass, Klass::vtable_length_offset()));
 
-  __ add(Rscan, Rclass, in_bytes(Klass::vtable_start_offset()));
-  __ add(Rscan, Rscan, AsmOperand(Rlength, lsl, scale));
-
-  // Search through the itable for an interface equal to incoming Ricklass
-  // itable looks like [intface][offset][intface][offset][intface][offset]
-  const int entry_size = itableOffsetEntry::size() * HeapWordSize;
-  assert(itableOffsetEntry::interface_offset_in_bytes() == 0, "not added for convenience");
+  Label L_no_such_interface;
 
-  Label loop;
-  __ bind(loop);
-  __ ldr(tmp, Address(Rscan, entry_size, post_indexed));
-#ifdef AARCH64
-  Label found;
-  __ cmp(tmp, Ricklass);
-  __ b(found, eq);
-  __ cbnz(tmp, loop);
-#else
-  __ cmp(tmp, Ricklass);  // set ZF and CF if interface is found
-  __ cmn(tmp, 0, ne);     // check if tmp == 0 and clear CF if it is
-  __ b(loop, ne);
-#endif // AARCH64
+  // Receiver subtype check against REFC.
+  __ ldr(Rintf, Address(Ricklass, CompiledICHolder::holder_klass_offset()));
+  __ lookup_interface_method(// inputs: rec. class, interface, itable index
+                             Rclass, Rintf, noreg,
+                             // outputs: temp reg1, temp reg2
+                             noreg, Rscan, Rtemp,
+                             L_no_such_interface);
 
-  assert(StubRoutines::throw_IncompatibleClassChangeError_entry() != NULL, "Check initialization order");
-#ifdef AARCH64
-  __ jump(StubRoutines::throw_IncompatibleClassChangeError_entry(), relocInfo::runtime_call_type, tmp);
-  __ bind(found);
-#else
-  // CF == 0 means we reached the end of itable without finding icklass
-  __ jump(StubRoutines::throw_IncompatibleClassChangeError_entry(), relocInfo::runtime_call_type, noreg, cc);
-#endif // !AARCH64
-
-  // Interface found at previous position of Rscan, now load the method oop
-  __ ldr_s32(tmp, Address(Rscan, itableOffsetEntry::offset_offset_in_bytes() - entry_size));
-  {
-    const int method_offset = itableMethodEntry::size() * HeapWordSize * itable_index +
-      itableMethodEntry::method_offset_in_bytes();
-    __ add_slow(Rmethod, Rclass, method_offset);
-  }
-  __ ldr(Rmethod, Address(Rmethod, tmp));
+  // Get Method* and entry point for compiler
+  __ ldr(Rintf, Address(Ricklass, CompiledICHolder::holder_metadata_offset()));
+  __ lookup_interface_method(// inputs: rec. class, interface, itable index
+                             Rclass, Rintf, itable_index,
+                             // outputs: temp reg1, temp reg2, temp reg3
+                             Rmethod, Rscan, Rtemp,
+                             L_no_such_interface);
 
   address ame_addr = __ pc();
 
 #ifdef AARCH64
-  __ ldr(tmp, Address(Rmethod, Method::from_compiled_offset()));
-  __ br(tmp);
+  __ ldr(Rtemp, Address(Rmethod, Method::from_compiled_offset()));
+  __ br(Rtemp);
 #else
   __ ldr(PC, Address(Rmethod, Method::from_compiled_offset()));
 #endif // AARCH64
 
+  __ bind(L_no_such_interface);
+
+  assert(StubRoutines::throw_IncompatibleClassChangeError_entry() != NULL, "check initialization order");
+  __ jump(StubRoutines::throw_IncompatibleClassChangeError_entry(), relocInfo::runtime_call_type, Rtemp);
+
   masm->flush();
 
   if (PrintMiscellaneous && (WizardMode || Verbose)) {
@@ -205,7 +187,7 @@
     instr_count = NOT_AARCH64(4) AARCH64_ONLY(5);
   } else {
     // itable stub size
-    instr_count = NOT_AARCH64(20) AARCH64_ONLY(20);
+    instr_count = NOT_AARCH64(31) AARCH64_ONLY(31);
   }
 
 #ifdef AARCH64
--- a/src/hotspot/cpu/ppc/macroAssembler_ppc.cpp	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/hotspot/cpu/ppc/macroAssembler_ppc.cpp	Fri Jan 12 15:05:35 2018 -0800
@@ -1788,11 +1788,10 @@
                                              RegisterOrConstant itable_index,
                                              Register method_result,
                                              Register scan_temp,
-                                             Register sethi_temp,
-                                             Label& L_no_such_interface) {
+                                             Register temp2,
+                                             Label& L_no_such_interface,
+                                             bool return_method) {
   assert_different_registers(recv_klass, intf_klass, method_result, scan_temp);
-  assert(itable_index.is_constant() || itable_index.as_register() == method_result,
-         "caller must use same register for non-constant itable index as for method");
 
   // Compute start of first itableOffsetEntry (which is at the end of the vtable).
   int vtable_base = in_bytes(Klass::vtable_start_offset());
@@ -1810,15 +1809,17 @@
   add(scan_temp, recv_klass, scan_temp);
 
   // Adjust recv_klass by scaled itable_index, so we can free itable_index.
-  if (itable_index.is_register()) {
-    Register itable_offset = itable_index.as_register();
-    sldi(itable_offset, itable_offset, logMEsize);
-    if (itentry_off) addi(itable_offset, itable_offset, itentry_off);
-    add(recv_klass, itable_offset, recv_klass);
-  } else {
-    long itable_offset = (long)itable_index.as_constant();
-    load_const_optimized(sethi_temp, (itable_offset<<logMEsize)+itentry_off); // static address, no relocation
-    add(recv_klass, sethi_temp, recv_klass);
+  if (return_method) {
+    if (itable_index.is_register()) {
+      Register itable_offset = itable_index.as_register();
+      sldi(method_result, itable_offset, logMEsize);
+      if (itentry_off) { addi(method_result, method_result, itentry_off); }
+      add(method_result, method_result, recv_klass);
+    } else {
+      long itable_offset = (long)itable_index.as_constant();
+      // static address, no relocation
+      add_const_optimized(method_result, recv_klass, (itable_offset << logMEsize) + itentry_off, temp2);
+    }
   }
 
   // for (scan = klass->itable(); scan->interface() != NULL; scan += scan_step) {
@@ -1831,12 +1832,12 @@
   for (int peel = 1; peel >= 0; peel--) {
     // %%%% Could load both offset and interface in one ldx, if they were
     // in the opposite order. This would save a load.
-    ld(method_result, itableOffsetEntry::interface_offset_in_bytes(), scan_temp);
+    ld(temp2, itableOffsetEntry::interface_offset_in_bytes(), scan_temp);
 
     // Check that this entry is non-null. A null entry means that
     // the receiver class doesn't implement the interface, and wasn't the
     // same as when the caller was compiled.
-    cmpd(CCR0, method_result, intf_klass);
+    cmpd(CCR0, temp2, intf_klass);
 
     if (peel) {
       beq(CCR0, found_method);
@@ -1849,7 +1850,7 @@
 
     bind(search);
 
-    cmpdi(CCR0, method_result, 0);
+    cmpdi(CCR0, temp2, 0);
     beq(CCR0, L_no_such_interface);
     addi(scan_temp, scan_temp, scan_step);
   }
@@ -1857,9 +1858,11 @@
   bind(found_method);
 
   // Got a hit.
-  int ito_offset = itableOffsetEntry::offset_offset_in_bytes();
-  lwz(scan_temp, ito_offset, scan_temp);
-  ldx(method_result, scan_temp, recv_klass);
+  if (return_method) {
+    int ito_offset = itableOffsetEntry::offset_offset_in_bytes();
+    lwz(scan_temp, ito_offset, scan_temp);
+    ldx(method_result, scan_temp, method_result);
+  }
 }
 
 // virtual method calling
--- a/src/hotspot/cpu/ppc/macroAssembler_ppc.hpp	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/hotspot/cpu/ppc/macroAssembler_ppc.hpp	Fri Jan 12 15:05:35 2018 -0800
@@ -519,7 +519,8 @@
                                RegisterOrConstant itable_index,
                                Register method_result,
                                Register temp_reg, Register temp2_reg,
-                               Label& no_such_interface);
+                               Label& no_such_interface,
+                               bool return_method = true);
 
   // virtual method calling
   void lookup_virtual_method(Register recv_klass,
--- a/src/hotspot/cpu/ppc/sharedRuntime_ppc.cpp	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/hotspot/cpu/ppc/sharedRuntime_ppc.cpp	Fri Jan 12 15:05:35 2018 -0800
@@ -1188,7 +1188,7 @@
   // Argument is valid and klass is as expected, continue.
 
   // Extract method from inline cache, verified entry point needs it.
-  __ ld(R19_method, CompiledICHolder::holder_method_offset(), ic);
+  __ ld(R19_method, CompiledICHolder::holder_metadata_offset(), ic);
   assert(R19_method == ic, "the inline cache register is dead here");
 
   __ ld(code, method_(code));
--- a/src/hotspot/cpu/ppc/templateTable_ppc_64.cpp	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/hotspot/cpu/ppc/templateTable_ppc_64.cpp	Fri Jan 12 15:05:35 2018 -0800
@@ -3486,11 +3486,11 @@
 void TemplateTable::invokeinterface_object_method(Register Rrecv_klass,
                                                   Register Rret,
                                                   Register Rflags,
-                                                  Register Rindex,
+                                                  Register Rmethod,
                                                   Register Rtemp1,
                                                   Register Rtemp2) {
 
-  assert_different_registers(Rindex, Rret, Rrecv_klass, Rflags, Rtemp1, Rtemp2);
+  assert_different_registers(Rmethod, Rret, Rrecv_klass, Rflags, Rtemp1, Rtemp2);
   Label LnotFinal;
 
   // Check for vfinal.
@@ -3502,14 +3502,14 @@
   // Final call case.
   __ profile_final_call(Rtemp1, Rscratch);
   // Argument and return type profiling.
-  __ profile_arguments_type(Rindex, Rscratch, Rrecv_klass /* scratch */, true);
+  __ profile_arguments_type(Rmethod, Rscratch, Rrecv_klass /* scratch */, true);
   // Do the final call - the index (f2) contains the method.
-  __ call_from_interpreter(Rindex, Rret, Rscratch, Rrecv_klass /* scratch */);
+  __ call_from_interpreter(Rmethod, Rret, Rscratch, Rrecv_klass /* scratch */);
 
   // Non-final callc case.
   __ bind(LnotFinal);
   __ profile_virtual_call(Rrecv_klass, Rtemp1, Rscratch, false);
-  generate_vtable_call(Rrecv_klass, Rindex, Rret, Rscratch);
+  generate_vtable_call(Rrecv_klass, Rmethod, Rret, Rscratch);
 }
 
 void TemplateTable::invokeinterface(int byte_no) {
@@ -3518,58 +3518,61 @@
 
   const Register Rscratch1        = R11_scratch1,
                  Rscratch2        = R12_scratch2,
-                 Rscratch3        = R9_ARG7,
-                 Rscratch4        = R10_ARG8,
-                 Rtable_addr      = Rscratch2,
+                 Rmethod          = R6_ARG4,
+                 Rmethod2         = R9_ARG7,
                  Rinterface_klass = R5_ARG3,
-                 Rret_type        = R8_ARG6,
-                 Rret_addr        = Rret_type,
-                 Rindex           = R6_ARG4,
-                 Rreceiver        = R4_ARG2,
-                 Rrecv_klass      = Rreceiver,
+                 Rret_addr        = R8_ARG6,
+                 Rindex           = R10_ARG8,
+                 Rreceiver        = R3_ARG1,
+                 Rrecv_klass      = R4_ARG2,
                  Rflags           = R7_ARG5;
 
-  prepare_invoke(byte_no, Rinterface_klass, Rret_addr, Rindex, Rreceiver, Rflags, Rscratch1);
+  prepare_invoke(byte_no, Rinterface_klass, Rret_addr, Rmethod, Rreceiver, Rflags, Rscratch1);
 
   // Get receiver klass.
-  __ null_check_throw(Rreceiver, oopDesc::klass_offset_in_bytes(), Rscratch3);
+  __ null_check_throw(Rreceiver, oopDesc::klass_offset_in_bytes(), Rscratch2);
   __ load_klass(Rrecv_klass, Rreceiver);
 
   // Check corner case object method.
-  Label LobjectMethod;
-
+  Label LobjectMethod, L_no_such_interface, Lthrow_ame;
   __ testbitdi(CCR0, R0, Rflags, ConstantPoolCacheEntry::is_forced_virtual_shift);
   __ btrue(CCR0, LobjectMethod);
 
-  // Fallthrough: The normal invokeinterface case.
+  __ lookup_interface_method(Rrecv_klass, Rinterface_klass, noreg, noreg, Rscratch1, Rscratch2,
+                             L_no_such_interface, /*return_method=*/false);
+
   __ profile_virtual_call(Rrecv_klass, Rscratch1, Rscratch2, false);
 
   // Find entry point to call.
-  Label Lthrow_icc, Lthrow_ame;
-  // Result will be returned in Rindex.
-  __ mr(Rscratch4, Rrecv_klass);
-  __ mr(Rscratch3, Rindex);
-  __ lookup_interface_method(Rrecv_klass, Rinterface_klass, Rindex, Rindex, Rscratch1, Rscratch2, Lthrow_icc);
-
-  __ cmpdi(CCR0, Rindex, 0);
+
+  // Get declaring interface class from method
+  __ ld(Rinterface_klass, in_bytes(Method::const_offset()), Rmethod);
+  __ ld(Rinterface_klass, in_bytes(ConstMethod::constants_offset()), Rinterface_klass);
+  __ ld(Rinterface_klass, ConstantPool::pool_holder_offset_in_bytes(), Rinterface_klass);
+
+  // Get itable index from method
+  __ lwa(Rindex, in_bytes(Method::itable_index_offset()), Rmethod);
+  __ subfic(Rindex, Rindex, Method::itable_index_max);
+
+  __ lookup_interface_method(Rrecv_klass, Rinterface_klass, Rindex, Rmethod2, Rscratch1, Rscratch2,
+                             L_no_such_interface);
+
+  __ cmpdi(CCR0, Rmethod2, 0);
   __ beq(CCR0, Lthrow_ame);
   // Found entry. Jump off!
   // Argument and return type profiling.
-  __ profile_arguments_type(Rindex, Rscratch1, Rscratch2, true);
-  __ call_from_interpreter(Rindex, Rret_addr, Rscratch1, Rscratch2);
+  __ profile_arguments_type(Rmethod2, Rscratch1, Rscratch2, true);
+  //__ profile_called_method(Rindex, Rscratch1);
+  __ call_from_interpreter(Rmethod2, Rret_addr, Rscratch1, Rscratch2);
 
   // Vtable entry was NULL => Throw abstract method error.
   __ bind(Lthrow_ame);
-  __ mr(Rrecv_klass, Rscratch4);
-  __ mr(Rindex, Rscratch3);
   call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_AbstractMethodError));
 
   // Interface was not found => Throw incompatible class change error.
-  __ bind(Lthrow_icc);
-  __ mr(Rrecv_klass, Rscratch4);
+  __ bind(L_no_such_interface);
   call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_IncompatibleClassChangeError));
-
-  __ should_not_reach_here();
+  DEBUG_ONLY( __ should_not_reach_here(); )
 
   // Special case of invokeinterface called for virtual method of
   // java.lang.Object. See ConstantPoolCacheEntry::set_method() for details:
@@ -3577,7 +3580,7 @@
   // to handle this corner case. This code isn't produced by javac, but could
   // be produced by another compliant java compiler.
   __ bind(LobjectMethod);
-  invokeinterface_object_method(Rrecv_klass, Rret_addr, Rflags, Rindex, Rscratch1, Rscratch2);
+  invokeinterface_object_method(Rrecv_klass, Rret_addr, Rflags, Rmethod, Rscratch1, Rscratch2);
 }
 
 void TemplateTable::invokedynamic(int byte_no) {
--- a/src/hotspot/cpu/ppc/vtableStubs_ppc_64.cpp	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/hotspot/cpu/ppc/vtableStubs_ppc_64.cpp	Fri Jan 12 15:05:35 2018 -0800
@@ -1,6 +1,6 @@
 /*
- * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
- * Copyright (c) 2012, 2016 SAP SE. All rights reserved.
+ * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2017 SAP SE. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -28,6 +28,7 @@
 #include "code/vtableStubs.hpp"
 #include "interp_masm_ppc.hpp"
 #include "memory/resourceArea.hpp"
+#include "oops/compiledICHolder.hpp"
 #include "oops/instanceKlass.hpp"
 #include "oops/klassVtable.hpp"
 #include "runtime/sharedRuntime.hpp"
@@ -55,17 +56,22 @@
   // PPC port: use fixed size.
   const int code_length = VtableStub::pd_code_size_limit(true);
   VtableStub* s = new (code_length) VtableStub(true, vtable_index);
+
+  // Can be NULL if there is no free space in the code cache.
+  if (s == NULL) {
+    return NULL;
+  }
+
   ResourceMark rm;
   CodeBuffer cb(s->entry_point(), code_length);
   MacroAssembler* masm = new MacroAssembler(&cb);
-  address start_pc;
 
 #ifndef PRODUCT
   if (CountCompiledCalls) {
-    __ load_const(R11_scratch1, SharedRuntime::nof_megamorphic_calls_addr());
-    __ lwz(R12_scratch2, 0, R11_scratch1);
+    int offs = __ load_const_optimized(R11_scratch1, SharedRuntime::nof_megamorphic_calls_addr(), R12_scratch2, true);
+    __ lwz(R12_scratch2, offs, R11_scratch1);
     __ addi(R12_scratch2, R12_scratch2, 1);
-    __ stw(R12_scratch2, 0, R11_scratch1);
+    __ stw(R12_scratch2, offs, R11_scratch1);
   }
 #endif
 
@@ -116,6 +122,7 @@
   __ ld(R12_scratch2, in_bytes(Method::from_compiled_offset()), R19_method);
   __ mtctr(R12_scratch2);
   __ bctr();
+
   masm->flush();
 
   guarantee(__ pc() <= s->code_end(), "overflowed buffer");
@@ -125,10 +132,16 @@
   return s;
 }
 
-VtableStub* VtableStubs::create_itable_stub(int vtable_index) {
+VtableStub* VtableStubs::create_itable_stub(int itable_index) {
   // PPC port: use fixed size.
   const int code_length = VtableStub::pd_code_size_limit(false);
-  VtableStub* s = new (code_length) VtableStub(false, vtable_index);
+  VtableStub* s = new (code_length) VtableStub(false, itable_index);
+
+  // Can be NULL if there is no free space in the code cache.
+  if (s == NULL) {
+    return NULL;
+  }
+
   ResourceMark rm;
   CodeBuffer cb(s->entry_point(), code_length);
   MacroAssembler* masm = new MacroAssembler(&cb);
@@ -136,10 +149,10 @@
 
 #ifndef PRODUCT
   if (CountCompiledCalls) {
-    __ load_const(R11_scratch1, SharedRuntime::nof_megamorphic_calls_addr());
-    __ lwz(R12_scratch2, 0, R11_scratch1);
+    int offs = __ load_const_optimized(R11_scratch1, SharedRuntime::nof_megamorphic_calls_addr(), R12_scratch2, true);
+    __ lwz(R12_scratch2, offs, R11_scratch1);
     __ addi(R12_scratch2, R12_scratch2, 1);
-    __ stw(R12_scratch2, 0, R11_scratch1);
+    __ stw(R12_scratch2, offs, R11_scratch1);
   }
 #endif
 
@@ -148,62 +161,28 @@
   // Entry arguments:
   //  R19_method: Interface
   //  R3_ARG1:    Receiver
-  //
 
-  const Register rcvr_klass = R11_scratch1;
-  const Register vtable_len = R12_scratch2;
-  const Register itable_entry_addr = R21_tmp1;
-  const Register itable_interface = R22_tmp2;
+  Label L_no_such_interface;
+  const Register rcvr_klass = R11_scratch1,
+                 interface  = R12_scratch2,
+                 tmp1       = R21_tmp1,
+                 tmp2       = R22_tmp2;
 
-  // Get receiver klass.
-
-  // We might implicit NULL fault here.
   address npe_addr = __ pc(); // npe = null pointer exception
   __ null_check(R3_ARG1, oopDesc::klass_offset_in_bytes(), /*implicit only*/NULL);
   __ load_klass(rcvr_klass, R3_ARG1);
 
-  BLOCK_COMMENT("Load start of itable entries into itable_entry.");
-  __ lwz(vtable_len, in_bytes(Klass::vtable_length_offset()), rcvr_klass);
-  __ slwi(vtable_len, vtable_len, exact_log2(vtableEntry::size_in_bytes()));
-  __ add(itable_entry_addr, vtable_len, rcvr_klass);
-
-  // Loop over all itable entries until desired interfaceOop(Rinterface) found.
-  BLOCK_COMMENT("Increment itable_entry_addr in loop.");
-  const int vtable_base_offset = in_bytes(Klass::vtable_start_offset());
-  __ addi(itable_entry_addr, itable_entry_addr, vtable_base_offset + itableOffsetEntry::interface_offset_in_bytes());
-
-  const int itable_offset_search_inc = itableOffsetEntry::size() * wordSize;
-  Label search;
-  __ bind(search);
-  __ ld(itable_interface, 0, itable_entry_addr);
+  // Receiver subtype check against REFC.
+  __ ld(interface, CompiledICHolder::holder_klass_offset(), R19_method);
+  __ lookup_interface_method(rcvr_klass, interface, noreg,
+                             R0, tmp1, tmp2,
+                             L_no_such_interface, /*return_method=*/ false);
 
-  // Handle IncompatibleClassChangeError in itable stubs.
-  // If the entry is NULL then we've reached the end of the table
-  // without finding the expected interface, so throw an exception.
-  BLOCK_COMMENT("Handle IncompatibleClassChangeError in itable stubs.");
-  Label throw_icce;
-  __ cmpdi(CCR1, itable_interface, 0);
-  __ cmpd(CCR0, itable_interface, R19_method);
-  __ addi(itable_entry_addr, itable_entry_addr, itable_offset_search_inc);
-  __ beq(CCR1, throw_icce);
-  __ bne(CCR0, search);
-
-  // Entry found and itable_entry_addr points to it, get offset of vtable for interface.
-
-  const Register vtable_offset = R12_scratch2;
-  const Register itable_method = R11_scratch1;
-
-  const int vtable_offset_offset = (itableOffsetEntry::offset_offset_in_bytes() -
-                                    itableOffsetEntry::interface_offset_in_bytes()) -
-                                   itable_offset_search_inc;
-  __ lwz(vtable_offset, vtable_offset_offset, itable_entry_addr);
-
-  // Compute itableMethodEntry and get method and entry point for compiler.
-  const int method_offset = (itableMethodEntry::size() * wordSize * vtable_index) +
-    itableMethodEntry::method_offset_in_bytes();
-
-  __ add(itable_method, rcvr_klass, vtable_offset);
-  __ ld(R19_method, method_offset, itable_method);
+  // Get Method* and entrypoint for compiler
+  __ ld(interface, CompiledICHolder::holder_metadata_offset(), R19_method);
+  __ lookup_interface_method(rcvr_klass, interface, itable_index,
+                             R19_method, tmp1, tmp2,
+                             L_no_such_interface, /*return_method=*/ true);
 
 #ifndef PRODUCT
   if (DebugVtables) {
@@ -219,7 +198,7 @@
   address ame_addr = __ pc(); // ame = abstract method error
 
   // Must do an explicit check if implicit checks are disabled.
-  __ null_check(R19_method, in_bytes(Method::from_compiled_offset()), &throw_icce);
+  __ null_check(R19_method, in_bytes(Method::from_compiled_offset()), &L_no_such_interface);
   __ ld(R12_scratch2, in_bytes(Method::from_compiled_offset()), R19_method);
   __ mtctr(R12_scratch2);
   __ bctr();
@@ -229,8 +208,8 @@
   // We force resolving of the call site by jumping to the "handle
   // wrong method" stub, and so let the interpreter runtime do all the
   // dirty work.
-  __ bind(throw_icce);
-  __ load_const(R11_scratch1, SharedRuntime::get_handle_wrong_method_stub());
+  __ bind(L_no_such_interface);
+  __ load_const_optimized(R11_scratch1, SharedRuntime::get_handle_wrong_method_stub(), R12_scratch2);
   __ mtctr(R11_scratch1);
   __ bctr();
 
@@ -245,14 +224,15 @@
 int VtableStub::pd_code_size_limit(bool is_vtable_stub) {
   if (DebugVtables || CountCompiledCalls || VerifyOops) {
     return 1000;
-  } else {
-    int decode_klass_size = MacroAssembler::instr_size_for_decode_klass_not_null();
-    if (is_vtable_stub) {
-      return 20 + decode_klass_size +  8 + 8;   // Plain + cOops + Traps + safety
-    } else {
-      return 96 + decode_klass_size + 12 + 8;   // Plain + cOops + Traps + safety
-    }
+  }
+  int size = is_vtable_stub ? 20 + 8 : 164 + 20; // Plain + safety
+  if (UseCompressedClassPointers) {
+    size += MacroAssembler::instr_size_for_decode_klass_not_null();
   }
+  if (!ImplicitNullChecks || !os::zero_page_read_protected()) {
+    size += is_vtable_stub ? 8 : 12;
+  }
+  return size;
 }
 
 int VtableStub::pd_code_alignment() {
--- a/src/hotspot/cpu/s390/macroAssembler_s390.cpp	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/hotspot/cpu/s390/macroAssembler_s390.cpp	Fri Jan 12 15:05:35 2018 -0800
@@ -2806,8 +2806,8 @@
                                              RegisterOrConstant itable_index,
                                              Register           method_result,
                                              Register           temp1_reg,
-                                             Register           temp2_reg,
-                                             Label&             no_such_interface) {
+                                             Label&             no_such_interface,
+                                             bool               return_method) {
 
   const Register vtable_len = temp1_reg;    // Used to compute itable_entry_addr.
   const Register itable_entry_addr = Z_R1_scratch;
@@ -2842,38 +2842,36 @@
   z_brne(search);
 
   // Entry found and itable_entry_addr points to it, get offset of vtable for interface.
-
-  const int vtable_offset_offset = (itableOffsetEntry::offset_offset_in_bytes() -
-                                    itableOffsetEntry::interface_offset_in_bytes()) -
-                                   itable_offset_search_inc;
-
-  // Compute itableMethodEntry and get method and entry point
-  // we use addressing with index and displacement, since the formula
-  // for computing the entry's offset has a fixed and a dynamic part,
-  // the latter depending on the matched interface entry and on the case,
-  // that the itable index has been passed as a register, not a constant value.
-  int method_offset = itableMethodEntry::method_offset_in_bytes();
-                           // Fixed part (displacement), common operand.
-  Register itable_offset;  // Dynamic part (index register).
-
-  if (itable_index.is_register()) {
-     // Compute the method's offset in that register, for the formula, see the
-     // else-clause below.
-     itable_offset = itable_index.as_register();
-
-     z_sllg(itable_offset, itable_offset, exact_log2(itableMethodEntry::size() * wordSize));
-     z_agf(itable_offset, vtable_offset_offset, itable_entry_addr);
-  } else {
-    itable_offset = Z_R1_scratch;
-    // Displacement increases.
-    method_offset += itableMethodEntry::size() * wordSize * itable_index.as_constant();
-
-    // Load index from itable.
-    z_llgf(itable_offset, vtable_offset_offset, itable_entry_addr);
-  }
-
-  // Finally load the method's oop.
-  z_lg(method_result, method_offset, itable_offset, recv_klass);
+  if (return_method) {
+    const int vtable_offset_offset = (itableOffsetEntry::offset_offset_in_bytes() -
+                                      itableOffsetEntry::interface_offset_in_bytes()) -
+                                     itable_offset_search_inc;
+
+    // Compute itableMethodEntry and get method and entry point
+    // we use addressing with index and displacement, since the formula
+    // for computing the entry's offset has a fixed and a dynamic part,
+    // the latter depending on the matched interface entry and on the case,
+    // that the itable index has been passed as a register, not a constant value.
+    int method_offset = itableMethodEntry::method_offset_in_bytes();
+                             // Fixed part (displacement), common operand.
+    Register itable_offset = method_result;  // Dynamic part (index register).
+
+    if (itable_index.is_register()) {
+       // Compute the method's offset in that register, for the formula, see the
+       // else-clause below.
+       z_sllg(itable_offset, itable_index.as_register(), exact_log2(itableMethodEntry::size() * wordSize));
+       z_agf(itable_offset, vtable_offset_offset, itable_entry_addr);
+    } else {
+      // Displacement increases.
+      method_offset += itableMethodEntry::size() * wordSize * itable_index.as_constant();
+
+      // Load index from itable.
+      z_llgf(itable_offset, vtable_offset_offset, itable_entry_addr);
+    }
+
+    // Finally load the method's oop.
+    z_lg(method_result, method_offset, itable_offset, recv_klass);
+  }
   BLOCK_COMMENT("} lookup_interface_method");
 }
 
--- a/src/hotspot/cpu/s390/macroAssembler_s390.hpp	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/hotspot/cpu/s390/macroAssembler_s390.hpp	Fri Jan 12 15:05:35 2018 -0800
@@ -671,8 +671,8 @@
                                RegisterOrConstant itable_index,
                                Register           method_result,
                                Register           temp1_reg,
-                               Register           temp2_reg,
-                               Label&             no_such_interface);
+                               Label&             no_such_interface,
+                               bool               return_method = true);
 
   // virtual method calling
   void lookup_virtual_method(Register             recv_klass,
--- a/src/hotspot/cpu/s390/methodHandles_s390.cpp	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/hotspot/cpu/s390/methodHandles_s390.cpp	Fri Jan 12 15:05:35 2018 -0800
@@ -498,7 +498,7 @@
       Label L_no_such_interface;
       __ lookup_interface_method(temp1_recv_klass, temp3_intf,
                                  // Note: next two args must be the same:
-                                 Z_index, Z_method, temp2, noreg,
+                                 Z_index, Z_method, temp2,
                                  L_no_such_interface);
       jump_from_method_handle(_masm, Z_method, temp2, Z_R0, for_compiler_entry);
 
--- a/src/hotspot/cpu/s390/sharedRuntime_s390.cpp	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/hotspot/cpu/s390/sharedRuntime_s390.cpp	Fri Jan 12 15:05:35 2018 -0800
@@ -2660,9 +2660,9 @@
   Label skip_fixup;
   {
     Label ic_miss;
-    const int klass_offset         = oopDesc::klass_offset_in_bytes();
-    const int holder_klass_offset  = CompiledICHolder::holder_klass_offset();
-    const int holder_method_offset = CompiledICHolder::holder_method_offset();
+    const int klass_offset           = oopDesc::klass_offset_in_bytes();
+    const int holder_klass_offset    = CompiledICHolder::holder_klass_offset();
+    const int holder_metadata_offset = CompiledICHolder::holder_metadata_offset();
 
     // Out-of-line call to ic_miss handler.
     __ call_ic_miss_handler(ic_miss, 0x11, 0, Z_R1_scratch);
@@ -2691,7 +2691,7 @@
     // This def MUST MATCH code in gen_c2i_adapter!
     const Register code = Z_R11;
 
-    __ z_lg(Z_method, holder_method_offset, Z_method);
+    __ z_lg(Z_method, holder_metadata_offset, Z_method);
     __ load_and_test_long(Z_R0, method_(code));
     __ z_brne(ic_miss);  // Cache miss: call runtime to handle this.
 
--- a/src/hotspot/cpu/s390/templateTable_s390.cpp	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/hotspot/cpu/s390/templateTable_s390.cpp	Fri Jan 12 15:05:35 2018 -0800
@@ -3557,66 +3557,67 @@
   transition(vtos, vtos);
 
   assert(byte_no == f1_byte, "use this argument");
-  Register interface = Z_tos;
-  Register index = Z_ARG3;
-  Register receiver = Z_tmp_1;
-  Register flags = Z_ARG5;
+  Register klass     = Z_ARG2,
+           method    = Z_ARG3,
+           interface = Z_ARG4,
+           flags     = Z_ARG5,
+           receiver  = Z_tmp_1;
 
   BLOCK_COMMENT("invokeinterface {");
 
-  // Destroys Z_ARG1 and Z_ARG2, thus use Z_ARG4 and copy afterwards.
-  prepare_invoke(byte_no, Z_ARG4, index,  // Get f1 klassOop, f2 itable index.
+  prepare_invoke(byte_no, interface, method,  // Get f1 klassOop, f2 itable index.
                  receiver, flags);
 
   // Z_R14 (== Z_bytecode) : return entry
 
-  __ z_lgr(interface, Z_ARG4);
-
   // Special case of invokeinterface called for virtual method of
   // java.lang.Object. See cpCacheOop.cpp for details.
   // This code isn't produced by javac, but could be produced by
   // another compliant java compiler.
-  Label notMethod;
+  NearLabel notMethod, no_such_interface, no_such_method;
   __ testbit(flags, ConstantPoolCacheEntry::is_forced_virtual_shift);
   __ z_brz(notMethod);
-  invokevirtual_helper(index, receiver, flags);
+  invokevirtual_helper(method, receiver, flags);
   __ bind(notMethod);
 
   // Get receiver klass into klass - also a null check.
-  Register klass = flags;
-
   __ restore_locals();
   __ load_klass(klass, receiver);
 
+  __ lookup_interface_method(klass, interface, noreg, noreg, /*temp*/Z_ARG1,
+                             no_such_interface, /*return_method=*/false);
+
   // Profile this call.
-  __ profile_virtual_call(klass, Z_ARG2/*mdp*/, Z_ARG4/*scratch*/);
-
-  NearLabel  no_such_interface, no_such_method;
-  Register   method = Z_tmp_2;
-
-  // TK 2010-08-24: save the index to Z_ARG4. needed in case of an error
-  //                in throw_AbstractMethodErrorByTemplateTable
-  __ z_lgr(Z_ARG4, index);
-  // TK 2011-03-24: copy also klass because it could be changed in
-  //                lookup_interface_method
-  __ z_lgr(Z_ARG2, klass);
-  __ lookup_interface_method(// inputs: rec. class, interface, itable index
-                              klass, interface, index,
-                              // outputs: method, scan temp. reg
-                              method, Z_tmp_2, Z_R1_scratch,
-                              no_such_interface);
+  __ profile_virtual_call(klass, Z_ARG1/*mdp*/, flags/*scratch*/);
+
+  // Find entry point to call.
+
+  // Get declaring interface class from method
+  __ z_lg(interface, Address(method, Method::const_offset()));
+  __ z_lg(interface, Address(interface, ConstMethod::constants_offset()));
+  __ z_lg(interface, Address(interface, ConstantPool::pool_holder_offset_in_bytes()));
+
+  // Get itable index from method
+  Register index   = receiver,
+           method2 = flags;
+  __ z_lgf(index, Address(method, Method::itable_index_offset()));
+  __ z_aghi(index, -Method::itable_index_max);
+  __ z_lcgr(index, index);
+
+  __ lookup_interface_method(klass, interface, index, method2, Z_tmp_2,
+                             no_such_interface);
 
   // Check for abstract method error.
   // Note: This should be done more efficiently via a throw_abstract_method_error
   // interpreter entry point and a conditional jump to it in case of a null
   // method.
-  __ compareU64_and_branch(method, (intptr_t) 0,
+  __ compareU64_and_branch(method2, (intptr_t) 0,
                             Assembler::bcondZero, no_such_method);
 
-  __ profile_arguments_type(Z_ARG3, method, Z_ARG5, true);
+  __ profile_arguments_type(Z_tmp_1, method2, Z_tmp_2, true);
 
   // Do the call.
-  __ jump_from_interpreted(method, Z_ARG5);
+  __ jump_from_interpreted(method2, Z_tmp_2);
   __ should_not_reach_here();
 
   // exception handling code follows...
@@ -3628,12 +3629,8 @@
   // Throw exception.
   __ restore_bcp();      // Bcp must be correct for exception handler   (was destroyed).
   __ restore_locals();   // Make sure locals pointer is correct as well (was destroyed).
-  // TK 2010-08-24: Call throw_AbstractMethodErrorByTemplateTable now with the
-  //                relevant information for generating a better error message
   __ call_VM(noreg,
-              CAST_FROM_FN_PTR(address,
-                               InterpreterRuntime::throw_AbstractMethodError),
-              Z_ARG2, interface, Z_ARG4);
+             CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_AbstractMethodError));
   // The call_VM checks for exception, so we should never return here.
   __ should_not_reach_here();
 
@@ -3642,12 +3639,8 @@
   // Throw exception.
   __ restore_bcp();      // Bcp must be correct for exception handler   (was destroyed).
   __ restore_locals();   // Make sure locals pointer is correct as well (was destroyed).
-  // TK 2010-08-24: Call throw_IncompatibleClassChangeErrorByTemplateTable now with the
-  //                relevant information for generating a better error message
   __ call_VM(noreg,
-             CAST_FROM_FN_PTR(address,
-                              InterpreterRuntime::throw_IncompatibleClassChangeError),
-             Z_ARG2, interface);
+             CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_IncompatibleClassChangeError));
   // The call_VM checks for exception, so we should never return here.
   __ should_not_reach_here();
 
--- a/src/hotspot/cpu/s390/vtableStubs_s390.cpp	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/hotspot/cpu/s390/vtableStubs_s390.cpp	Fri Jan 12 15:05:35 2018 -0800
@@ -1,6 +1,6 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
- * Copyright (c) 2016 SAP SE. All rights reserved.
+ * Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017 SAP SE. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -28,6 +28,7 @@
 #include "code/vtableStubs.hpp"
 #include "interp_masm_s390.hpp"
 #include "memory/resourceArea.hpp"
+#include "oops/compiledICHolder.hpp"
 #include "oops/instanceKlass.hpp"
 #include "oops/klassVtable.hpp"
 #include "runtime/sharedRuntime.hpp"
@@ -57,7 +58,6 @@
   ResourceMark    rm;
   CodeBuffer      cb(s->entry_point(), code_length);
   MacroAssembler *masm = new MacroAssembler(&cb);
-  address start_pc;
   int     padding_bytes = 0;
 
 #if (!defined(PRODUCT) && defined(COMPILER2))
@@ -144,9 +144,9 @@
   return s;
 }
 
-VtableStub* VtableStubs::create_itable_stub(int vtable_index) {
+VtableStub* VtableStubs::create_itable_stub(int itable_index) {
   const int   code_length = VtableStub::pd_code_size_limit(false);
-  VtableStub *s = new(code_length) VtableStub(false, vtable_index);
+  VtableStub *s = new(code_length) VtableStub(false, itable_index);
   if (s == NULL) { // Indicates OOM in the code cache.
     return NULL;
   }
@@ -154,7 +154,6 @@
   ResourceMark    rm;
   CodeBuffer      cb(s->entry_point(), code_length);
   MacroAssembler *masm = new MacroAssembler(&cb);
-  address start_pc;
   int     padding_bytes = 0;
 
 #if (!defined(PRODUCT) && defined(COMPILER2))
@@ -174,11 +173,9 @@
   // Entry arguments:
   //  Z_method: Interface
   //  Z_ARG1:   Receiver
-  const Register rcvr_klass = Z_tmp_1;    // Used to compute itable_entry_addr.
-                                          // Use extra reg to avoid re-load.
-  const Register vtable_len = Z_tmp_2;    // Used to compute itable_entry_addr.
-  const Register itable_entry_addr = Z_R1_scratch;
-  const Register itable_interface  = Z_R0_scratch;
+  NearLabel no_such_interface;
+  const Register rcvr_klass = Z_tmp_1,
+                 interface  = Z_tmp_2;
 
   // Get receiver klass.
   // Must do an explicit check if implicit checks are disabled.
@@ -186,50 +183,15 @@
   __ null_check(Z_ARG1, Z_R1_scratch, oopDesc::klass_offset_in_bytes());
   __ load_klass(rcvr_klass, Z_ARG1);
 
-  // Load start of itable entries into itable_entry.
-  __ z_llgf(vtable_len, Address(rcvr_klass, Klass::vtable_length_offset()));
-  __ z_sllg(vtable_len, vtable_len, exact_log2(vtableEntry::size_in_bytes()));
-
-  // Loop over all itable entries until desired interfaceOop(Rinterface) found.
-  const int vtable_base_offset = in_bytes(Klass::vtable_start_offset());
-  // Count unused bytes.
-  start_pc = __ pc();
-  __ add2reg_with_index(itable_entry_addr, vtable_base_offset + itableOffsetEntry::interface_offset_in_bytes(), rcvr_klass, vtable_len);
-  padding_bytes += 20 - (__ pc() - start_pc);
-
-  const int itable_offset_search_inc = itableOffsetEntry::size() * wordSize;
-  Label search;
-  __ bind(search);
+  // Receiver subtype check against REFC.
+  __ z_lg(interface, Address(Z_method, CompiledICHolder::holder_klass_offset()));
+  __ lookup_interface_method(rcvr_klass, interface, noreg,
+                             noreg, Z_R1, no_such_interface, /*return_method=*/ false);
 
-  // Handle IncompatibleClassChangeError in itable stubs.
-  // If the entry is NULL then we've reached the end of the table
-  // without finding the expected interface, so throw an exception.
-  NearLabel   throw_icce;
-  __ load_and_test_long(itable_interface, Address(itable_entry_addr));
-  __ z_bre(throw_icce); // Throw the exception out-of-line.
-  // Count unused bytes.
-  start_pc = __ pc();
-  __ add2reg(itable_entry_addr, itable_offset_search_inc);
-  padding_bytes += 20 - (__ pc() - start_pc);
-  __ z_cgr(itable_interface, Z_method);
-  __ z_brne(search);
-
-  // Entry found. Itable_entry_addr points to the subsequent entry (itable_offset_search_inc too far).
-  // Get offset of vtable for interface.
-
-  const Register vtable_offset = Z_R1_scratch;
-  const Register itable_method = rcvr_klass;   // Calculated before.
-
-  const int vtable_offset_offset = (itableOffsetEntry::offset_offset_in_bytes() -
-                                    itableOffsetEntry::interface_offset_in_bytes()) -
-                                   itable_offset_search_inc;
-  __ z_llgf(vtable_offset, vtable_offset_offset, itable_entry_addr);
-
-  // Compute itableMethodEntry and get method and entry point for compiler.
-  const int method_offset = (itableMethodEntry::size() * wordSize * vtable_index) +
-                            itableMethodEntry::method_offset_in_bytes();
-
-  __ z_lg(Z_method, method_offset, vtable_offset, itable_method);
+  // Get Method* and entrypoint for compiler
+  __ z_lg(interface, Address(Z_method, CompiledICHolder::holder_metadata_offset()));
+  __ lookup_interface_method(rcvr_klass, interface, itable_index,
+                             Z_method, Z_R1, no_such_interface, /*return_method=*/ true);
 
 #ifndef PRODUCT
   if (DebugVtables) {
@@ -244,13 +206,13 @@
   address ame_addr = __ pc();
   // Must do an explicit check if implicit checks are disabled.
   if (!ImplicitNullChecks) {
-    __ compare64_and_branch(Z_method, (intptr_t) 0, Assembler::bcondEqual, throw_icce);
+    __ compare64_and_branch(Z_method, (intptr_t) 0, Assembler::bcondEqual, no_such_interface);
   }
   __ z_lg(Z_R1_scratch, in_bytes(Method::from_compiled_offset()), Z_method);
   __ z_br(Z_R1_scratch);
 
   // Handle IncompatibleClassChangeError in itable stubs.
-  __ bind(throw_icce);
+  __ bind(no_such_interface);
   // Count unused bytes
   //                  worst case          actual size
   // We force resolving of the call site by jumping to
@@ -273,13 +235,12 @@
   if (CountCompiledCalls) {
     size += 6 * 4;
   }
-  if (is_vtable_stub) {
-    size += 52;
-  } else {
-    size += 104;
+  size += is_vtable_stub ? 36 : 140;
+  if (UseCompressedClassPointers) {
+    size += MacroAssembler::instr_size_for_decode_klass_not_null();
   }
-  if (Universe::narrow_klass_base() != NULL) {
-    size += 16; // A guess.
+  if (!ImplicitNullChecks) {
+    size += 36;
   }
   return size;
 }
--- a/src/hotspot/cpu/sparc/macroAssembler_sparc.cpp	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/hotspot/cpu/sparc/macroAssembler_sparc.cpp	Fri Jan 12 15:05:35 2018 -0800
@@ -2058,9 +2058,10 @@
                                              Register method_result,
                                              Register scan_temp,
                                              Register sethi_temp,
-                                             Label& L_no_such_interface) {
+                                             Label& L_no_such_interface,
+                                             bool return_method) {
   assert_different_registers(recv_klass, intf_klass, method_result, scan_temp);
-  assert(itable_index.is_constant() || itable_index.as_register() == method_result,
+  assert(!return_method || itable_index.is_constant() || itable_index.as_register() == method_result,
          "caller must use same register for non-constant itable index as for method");
 
   Label L_no_such_interface_restore;
@@ -2092,11 +2093,13 @@
   add(scan_temp, itb_offset, scan_temp);
   add(recv_klass, scan_temp, scan_temp);
 
-  // Adjust recv_klass by scaled itable_index, so we can free itable_index.
-  RegisterOrConstant itable_offset = itable_index;
-  itable_offset = regcon_sll_ptr(itable_index, exact_log2(itableMethodEntry::size() * wordSize), itable_offset);
-  itable_offset = regcon_inc_ptr(itable_offset, itableMethodEntry::method_offset_in_bytes(), itable_offset);
-  add(recv_klass, ensure_simm13_or_reg(itable_offset, sethi_temp), recv_klass);
+  if (return_method) {
+    // Adjust recv_klass by scaled itable_index, so we can free itable_index.
+    RegisterOrConstant itable_offset = itable_index;
+    itable_offset = regcon_sll_ptr(itable_index, exact_log2(itableMethodEntry::size() * wordSize), itable_offset);
+    itable_offset = regcon_inc_ptr(itable_offset, itableMethodEntry::method_offset_in_bytes(), itable_offset);
+    add(recv_klass, ensure_simm13_or_reg(itable_offset, sethi_temp), recv_klass);
+  }
 
   // for (scan = klass->itable(); scan->interface() != NULL; scan += scan_step) {
   //   if (scan->interface() == intf) {
@@ -2131,12 +2134,14 @@
 
   bind(L_found_method);
 
-  // Got a hit.
-  int ito_offset = itableOffsetEntry::offset_offset_in_bytes();
-  // scan_temp[-scan_step] points to the vtable offset we need
-  ito_offset -= scan_step;
-  lduw(scan_temp, ito_offset, scan_temp);
-  ld_ptr(recv_klass, scan_temp, method_result);
+  if (return_method) {
+    // Got a hit.
+    int ito_offset = itableOffsetEntry::offset_offset_in_bytes();
+    // scan_temp[-scan_step] points to the vtable offset we need
+    ito_offset -= scan_step;
+    lduw(scan_temp, ito_offset, scan_temp);
+    ld_ptr(recv_klass, scan_temp, method_result);
+  }
 
   if (did_save) {
     Label L_done;
--- a/src/hotspot/cpu/sparc/macroAssembler_sparc.hpp	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/hotspot/cpu/sparc/macroAssembler_sparc.hpp	Fri Jan 12 15:05:35 2018 -0800
@@ -1277,7 +1277,8 @@
                                RegisterOrConstant itable_index,
                                Register method_result,
                                Register temp_reg, Register temp2_reg,
-                               Label& no_such_interface);
+                               Label& no_such_interface,
+                               bool return_method = true);
 
   // virtual method calling
   void lookup_virtual_method(Register recv_klass,
--- a/src/hotspot/cpu/sparc/sharedRuntime_sparc.cpp	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/hotspot/cpu/sparc/sharedRuntime_sparc.cpp	Fri Jan 12 15:05:35 2018 -0800
@@ -904,7 +904,7 @@
 
     Label ok, ok2;
     __ brx(Assembler::equal, false, Assembler::pt, ok);
-    __ delayed()->ld_ptr(G5_method, CompiledICHolder::holder_method_offset(), G5_method);
+    __ delayed()->ld_ptr(G5_method, CompiledICHolder::holder_metadata_offset(), G5_method);
     __ jump_to(ic_miss, G3_scratch);
     __ delayed()->nop();
 
--- a/src/hotspot/cpu/sparc/templateTable_sparc.cpp	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/hotspot/cpu/sparc/templateTable_sparc.cpp	Fri Jan 12 15:05:35 2018 -0800
@@ -3081,15 +3081,15 @@
   assert(byte_no == f1_byte, "use this argument");
 
   const Register Rinterface  = G1_scratch;
+  const Register Rmethod     = Lscratch;
   const Register Rret        = G3_scratch;
-  const Register Rindex      = Lscratch;
   const Register O0_recv     = O0;
   const Register O1_flags    = O1;
   const Register O2_Klass    = O2;
   const Register Rscratch    = G4_scratch;
   assert_different_registers(Rscratch, G5_method);
 
-  prepare_invoke(byte_no, Rinterface, Rret, Rindex, O0_recv, O1_flags);
+  prepare_invoke(byte_no, Rinterface, Rret, Rmethod, O0_recv, O1_flags);
 
   // get receiver klass
   __ null_check(O0_recv, oopDesc::klass_offset_in_bytes());
@@ -3109,55 +3109,40 @@
 
   __ bind(notMethod);
 
+  Register Rtemp = O1_flags;
+
+  Label L_no_such_interface;
+
+  // Receiver subtype check against REFC.
+  __ lookup_interface_method(// inputs: rec. class, interface, itable index
+                             O2_Klass, Rinterface, noreg,
+                             // outputs: temp reg1, temp reg2, temp reg3
+                             G5_method, Rscratch, Rtemp,
+                             L_no_such_interface,
+                             /*return_method=*/false);
+
   __ profile_virtual_call(O2_Klass, O4);
 
   //
   // find entry point to call
   //
 
-  // compute start of first itableOffsetEntry (which is at end of vtable)
-  const int base = in_bytes(Klass::vtable_start_offset());
-  Label search;
-  Register Rtemp = O1_flags;
-
-  __ ld(O2_Klass, in_bytes(Klass::vtable_length_offset()), Rtemp);
-  __ sll(Rtemp, LogBytesPerWord, Rtemp);   // Rscratch *= 4;
-  if (Assembler::is_simm13(base)) {
-    __ add(Rtemp, base, Rtemp);
-  } else {
-    __ set(base, Rscratch);
-    __ add(Rscratch, Rtemp, Rtemp);
-  }
-  __ add(O2_Klass, Rtemp, Rscratch);
-
-  __ bind(search);
-
-  __ ld_ptr(Rscratch, itableOffsetEntry::interface_offset_in_bytes(), Rtemp);
-  {
-    Label ok;
-
-    // Check that entry is non-null.  Null entries are probably a bytecode
-    // problem.  If the interface isn't implemented by the receiver class,
-    // the VM should throw IncompatibleClassChangeError.  linkResolver checks
-    // this too but that's only if the entry isn't already resolved, so we
-    // need to check again.
-    __ br_notnull_short( Rtemp, Assembler::pt, ok);
-    call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_IncompatibleClassChangeError));
-    __ should_not_reach_here();
-    __ bind(ok);
-  }
-
-  __ cmp(Rinterface, Rtemp);
-  __ brx(Assembler::notEqual, true, Assembler::pn, search);
-  __ delayed()->add(Rscratch, itableOffsetEntry::size() * wordSize, Rscratch);
-
-  // entry found and Rscratch points to it
-  __ ld(Rscratch, itableOffsetEntry::offset_offset_in_bytes(), Rscratch);
-
-  assert(itableMethodEntry::method_offset_in_bytes() == 0, "adjust instruction below");
-  __ sll(Rindex, exact_log2(itableMethodEntry::size() * wordSize), Rindex);       // Rindex *= 8;
-  __ add(Rscratch, Rindex, Rscratch);
-  __ ld_ptr(O2_Klass, Rscratch, G5_method);
+  // Get declaring interface class from method
+  __ ld_ptr(Rmethod, Method::const_offset(), Rinterface);
+  __ ld_ptr(Rinterface, ConstMethod::constants_offset(), Rinterface);
+  __ ld_ptr(Rinterface, ConstantPool::pool_holder_offset_in_bytes(), Rinterface);
+
+  // Get itable index from method
+  const Register Rindex = G5_method;
+  __ ld(Rmethod, Method::itable_index_offset(), Rindex);
+  __ sub(Rindex, Method::itable_index_max, Rindex);
+  __ neg(Rindex);
+
+  __ lookup_interface_method(// inputs: rec. class, interface, itable index
+                             O2_Klass, Rinterface, Rindex,
+                             // outputs: method, scan temp reg, temp reg
+                             G5_method, Rscratch, Rtemp,
+                             L_no_such_interface);
 
   // Check for abstract method error.
   {
@@ -3174,6 +3159,10 @@
   __ profile_arguments_type(G5_method, Rcall, Gargs, true);
   __ profile_called_method(G5_method, Rscratch);
   __ call_from_interpreter(Rcall, Gargs, Rret);
+
+  __ bind(L_no_such_interface);
+  call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_IncompatibleClassChangeError));
+  __ should_not_reach_here();
 }
 
 void TemplateTable::invokehandle(int byte_no) {
--- a/src/hotspot/cpu/sparc/vtableStubs_sparc.cpp	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/hotspot/cpu/sparc/vtableStubs_sparc.cpp	Fri Jan 12 15:05:35 2018 -0800
@@ -27,6 +27,7 @@
 #include "code/vtableStubs.hpp"
 #include "interp_masm_sparc.hpp"
 #include "memory/resourceArea.hpp"
+#include "oops/compiledICHolder.hpp"
 #include "oops/instanceKlass.hpp"
 #include "oops/klassVtable.hpp"
 #include "runtime/sharedRuntime.hpp"
@@ -140,7 +141,8 @@
   MacroAssembler* masm = new MacroAssembler(&cb);
 
   Register G3_Klass = G3_scratch;
-  Register G5_interface = G5;  // Passed in as an argument
+  Register G5_icholder = G5;  // Passed in as an argument
+  Register G4_interface = G4_scratch;
   Label search;
 
   // Entry arguments:
@@ -164,14 +166,26 @@
   }
 #endif /* PRODUCT */
 
-  Label throw_icce;
+  Label L_no_such_interface;
 
   Register L5_method = L5;
+
+  // Receiver subtype check against REFC.
+  __ ld_ptr(G5_icholder, CompiledICHolder::holder_klass_offset(), G4_interface);
   __ lookup_interface_method(// inputs: rec. class, interface, itable index
-                             G3_Klass, G5_interface, itable_index,
+                             G3_Klass, G4_interface, itable_index,
+                             // outputs: scan temp. reg1, scan temp. reg2
+                             L5_method, L2, L3,
+                             L_no_such_interface,
+                             /*return_method=*/ false);
+
+  // Get Method* and entrypoint for compiler
+  __ ld_ptr(G5_icholder, CompiledICHolder::holder_metadata_offset(), G4_interface);
+  __ lookup_interface_method(// inputs: rec. class, interface, itable index
+                             G3_Klass, G4_interface, itable_index,
                              // outputs: method, scan temp. reg
                              L5_method, L2, L3,
-                             throw_icce);
+                             L_no_such_interface);
 
 #ifndef PRODUCT
   if (DebugVtables) {
@@ -197,7 +211,7 @@
   __ JMP(G3_scratch, 0);
   __ delayed()->nop();
 
-  __ bind(throw_icce);
+  __ bind(L_no_such_interface);
   AddressLiteral icce(StubRoutines::throw_IncompatibleClassChangeError_entry());
   __ jump_to(icce, G3_scratch);
   __ delayed()->restore();
@@ -232,7 +246,7 @@
                           MacroAssembler::instr_size_for_decode_klass_not_null() : 0);
       return basic + slop;
     } else {
-      const int basic = 34 * BytesPerInstWord +
+      const int basic = 54 * BytesPerInstWord +
                         // shift;add for load_klass (only shift with zero heap based)
                         (UseCompressedClassPointers ?
                           MacroAssembler::instr_size_for_decode_klass_not_null() : 0);
--- a/src/hotspot/cpu/x86/macroAssembler_x86.cpp	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/hotspot/cpu/x86/macroAssembler_x86.cpp	Fri Jan 12 15:05:35 2018 -0800
@@ -5809,8 +5809,13 @@
                                              RegisterOrConstant itable_index,
                                              Register method_result,
                                              Register scan_temp,
-                                             Label& L_no_such_interface) {
-  assert_different_registers(recv_klass, intf_klass, method_result, scan_temp);
+                                             Label& L_no_such_interface,
+                                             bool return_method) {
+  assert_different_registers(recv_klass, intf_klass, scan_temp);
+  assert_different_registers(method_result, intf_klass, scan_temp);
+  assert(recv_klass != method_result || !return_method,
+         "recv_klass can be destroyed when method isn't needed");
+
   assert(itable_index.is_constant() || itable_index.as_register() == method_result,
          "caller must use same register for non-constant itable index as for method");
 
@@ -5827,9 +5832,11 @@
   // %%% Could store the aligned, prescaled offset in the klassoop.
   lea(scan_temp, Address(recv_klass, scan_temp, times_vte_scale, vtable_base));
 
-  // Adjust recv_klass by scaled itable_index, so we can free itable_index.
-  assert(itableMethodEntry::size() * wordSize == wordSize, "adjust the scaling in the code below");
-  lea(recv_klass, Address(recv_klass, itable_index, Address::times_ptr, itentry_off));
+  if (return_method) {
+    // Adjust recv_klass by scaled itable_index, so we can free itable_index.
+    assert(itableMethodEntry::size() * wordSize == wordSize, "adjust the scaling in the code below");
+    lea(recv_klass, Address(recv_klass, itable_index, Address::times_ptr, itentry_off));
+  }
 
   // for (scan = klass->itable(); scan->interface() != NULL; scan += scan_step) {
   //   if (scan->interface() == intf) {
@@ -5863,9 +5870,11 @@
 
   bind(found_method);
 
-  // Got a hit.
-  movl(scan_temp, Address(scan_temp, itableOffsetEntry::offset_offset_in_bytes()));
-  movptr(method_result, Address(recv_klass, scan_temp, Address::times_1));
+  if (return_method) {
+    // Got a hit.
+    movl(scan_temp, Address(scan_temp, itableOffsetEntry::offset_offset_in_bytes()));
+    movptr(method_result, Address(recv_klass, scan_temp, Address::times_1));
+  }
 }
 
 
--- a/src/hotspot/cpu/x86/macroAssembler_x86.hpp	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/hotspot/cpu/x86/macroAssembler_x86.hpp	Fri Jan 12 15:05:35 2018 -0800
@@ -544,7 +544,8 @@
                                RegisterOrConstant itable_index,
                                Register method_result,
                                Register scan_temp,
-                               Label& no_such_interface);
+                               Label& no_such_interface,
+                               bool return_method = true);
 
   // virtual method calling
   void lookup_virtual_method(Register recv_klass,
--- a/src/hotspot/cpu/x86/sharedRuntime_x86_32.cpp	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/hotspot/cpu/x86/sharedRuntime_x86_32.cpp	Fri Jan 12 15:05:35 2018 -0800
@@ -957,7 +957,7 @@
     Label missed;
     __ movptr(temp, Address(receiver, oopDesc::klass_offset_in_bytes()));
     __ cmpptr(temp, Address(holder, CompiledICHolder::holder_klass_offset()));
-    __ movptr(rbx, Address(holder, CompiledICHolder::holder_method_offset()));
+    __ movptr(rbx, Address(holder, CompiledICHolder::holder_metadata_offset()));
     __ jcc(Assembler::notEqual, missed);
     // Method might have been compiled since the call site was patched to
     // interpreted if that is the case treat it as a miss so we can get
--- a/src/hotspot/cpu/x86/sharedRuntime_x86_64.cpp	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/hotspot/cpu/x86/sharedRuntime_x86_64.cpp	Fri Jan 12 15:05:35 2018 -0800
@@ -949,7 +949,7 @@
   {
     __ load_klass(temp, receiver);
     __ cmpptr(temp, Address(holder, CompiledICHolder::holder_klass_offset()));
-    __ movptr(rbx, Address(holder, CompiledICHolder::holder_method_offset()));
+    __ movptr(rbx, Address(holder, CompiledICHolder::holder_metadata_offset()));
     __ jcc(Assembler::equal, ok);
     __ jump(RuntimeAddress(SharedRuntime::get_ic_miss_stub()));
 
--- a/src/hotspot/cpu/x86/templateTable_x86.cpp	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/hotspot/cpu/x86/templateTable_x86.cpp	Fri Jan 12 15:05:35 2018 -0800
@@ -3712,11 +3712,11 @@
 void TemplateTable::invokeinterface(int byte_no) {
   transition(vtos, vtos);
   assert(byte_no == f1_byte, "use this argument");
-  prepare_invoke(byte_no, rax, rbx,  // get f1 Klass*, f2 itable index
+  prepare_invoke(byte_no, rax, rbx,  // get f1 Klass*, f2 Method*
                  rcx, rdx); // recv, flags
 
-  // rax: interface klass (from f1)
-  // rbx: itable index (from f2)
+  // rax: reference klass (from f1)
+  // rbx: method (from f2)
   // rcx: receiver
   // rdx: flags
 
@@ -3738,10 +3738,28 @@
   __ null_check(rcx, oopDesc::klass_offset_in_bytes());
   __ load_klass(rdx, rcx);
 
+  Label no_such_interface, no_such_method;
+
+  // Receiver subtype check against REFC.
+  // Superklass in rax. Subklass in rdx. Blows rcx, rdi.
+  __ lookup_interface_method(// inputs: rec. class, interface, itable index
+                             rdx, rax, noreg,
+                             // outputs: scan temp. reg, scan temp. reg
+                             rbcp, rlocals,
+                             no_such_interface,
+                             /*return_method=*/false);
+
   // profile this call
+  __ restore_bcp(); // rbcp was destroyed by receiver type check
   __ profile_virtual_call(rdx, rbcp, rlocals);
 
-  Label no_such_interface, no_such_method;
+  // Get declaring interface class from method, and itable index
+  __ movptr(rax, Address(rbx, Method::const_offset()));
+  __ movptr(rax, Address(rax, ConstMethod::constants_offset()));
+  __ movptr(rax, Address(rax, ConstantPool::pool_holder_offset_in_bytes()));
+  __ movl(rbx, Address(rbx, Method::itable_index_offset()));
+  __ subl(rbx, Method::itable_index_max);
+  __ negl(rbx);
 
   __ lookup_interface_method(// inputs: rec. class, interface, itable index
                              rdx, rax, rbx,
--- a/src/hotspot/cpu/x86/vtableStubs_x86_32.cpp	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/hotspot/cpu/x86/vtableStubs_x86_32.cpp	Fri Jan 12 15:05:35 2018 -0800
@@ -27,6 +27,7 @@
 #include "code/vtableStubs.hpp"
 #include "interp_masm_x86.hpp"
 #include "memory/resourceArea.hpp"
+#include "oops/compiledICHolder.hpp"
 #include "oops/instanceKlass.hpp"
 #include "oops/klassVtable.hpp"
 #include "runtime/sharedRuntime.hpp"
@@ -147,7 +148,7 @@
   MacroAssembler* masm = new MacroAssembler(&cb);
 
   // Entry arguments:
-  //  rax,: Interface
+  //  rax: CompiledICHolder
   //  rcx: Receiver
 
 #ifndef PRODUCT
@@ -155,25 +156,42 @@
     __ incrementl(ExternalAddress((address) SharedRuntime::nof_megamorphic_calls_addr()));
   }
 #endif /* PRODUCT */
-  // get receiver (need to skip return address on top of stack)
-
-  assert(VtableStub::receiver_location() == rcx->as_VMReg(), "receiver expected in rcx");
-
-  // get receiver klass (also an implicit null-check)
-  address npe_addr = __ pc();
-  __ movptr(rsi, Address(rcx, oopDesc::klass_offset_in_bytes()));
 
   // Most registers are in use; we'll use rax, rbx, rsi, rdi
   // (If we need to make rsi, rdi callee-save, do a push/pop here.)
+  const Register recv_klass_reg     = rsi;
+  const Register holder_klass_reg   = rax; // declaring interface klass (DECC)
+  const Register resolved_klass_reg = rbx; // resolved interface klass (REFC)
+  const Register temp_reg           = rdi;
+
+  const Register icholder_reg = rax;
+  __ movptr(resolved_klass_reg, Address(icholder_reg, CompiledICHolder::holder_klass_offset()));
+  __ movptr(holder_klass_reg,   Address(icholder_reg, CompiledICHolder::holder_metadata_offset()));
+
+  Label L_no_such_interface;
+
+  // get receiver klass (also an implicit null-check)
+  address npe_addr = __ pc();
+  assert(VtableStub::receiver_location() ==  rcx->as_VMReg(), "receiver expected in  rcx");
+  __ load_klass(recv_klass_reg, rcx);
+
+  // Receiver subtype check against REFC.
+  // Destroys recv_klass_reg value.
+  __ lookup_interface_method(// inputs: rec. class, interface
+                             recv_klass_reg, resolved_klass_reg, noreg,
+                             // outputs:  scan temp. reg1, scan temp. reg2
+                             recv_klass_reg, temp_reg,
+                             L_no_such_interface,
+                             /*return_method=*/false);
+
+  // Get selected method from declaring class and itable index
   const Register method = rbx;
-  Label throw_icce;
-
-  // Get Method* and entrypoint for compiler
+  __ load_klass(recv_klass_reg, rcx); // restore recv_klass_reg
   __ lookup_interface_method(// inputs: rec. class, interface, itable index
-                             rsi, rax, itable_index,
+                             recv_klass_reg, holder_klass_reg, itable_index,
                              // outputs: method, scan temp. reg
-                             method, rdi,
-                             throw_icce);
+                             method, temp_reg,
+                             L_no_such_interface);
 
   // method (rbx): Method*
   // rcx: receiver
@@ -193,9 +211,10 @@
   address ame_addr = __ pc();
   __ jmp(Address(method, Method::from_compiled_offset()));
 
-  __ bind(throw_icce);
+  __ bind(L_no_such_interface);
   __ jump(RuntimeAddress(StubRoutines::throw_IncompatibleClassChangeError_entry()));
-  masm->flush();
+
+  __ flush();
 
   if (PrintMiscellaneous && (WizardMode || Verbose)) {
     tty->print_cr("itable #%d at " PTR_FORMAT "[%d] left over: %d",
@@ -220,7 +239,7 @@
     return (DebugVtables ? 210 : 16) + (CountCompiledCalls ? 6 : 0);
   } else {
     // Itable stub size
-    return (DebugVtables ? 256 : 66) + (CountCompiledCalls ? 6 : 0);
+    return (DebugVtables ? 256 : 110) + (CountCompiledCalls ? 6 : 0);
   }
   // In order to tune these parameters, run the JVM with VM options
   // +PrintMiscellaneous and +WizardMode to see information about
--- a/src/hotspot/cpu/x86/vtableStubs_x86_64.cpp	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/hotspot/cpu/x86/vtableStubs_x86_64.cpp	Fri Jan 12 15:05:35 2018 -0800
@@ -27,6 +27,7 @@
 #include "code/vtableStubs.hpp"
 #include "interp_masm_x86.hpp"
 #include "memory/resourceArea.hpp"
+#include "oops/compiledICHolder.hpp"
 #include "oops/instanceKlass.hpp"
 #include "oops/klassVtable.hpp"
 #include "runtime/sharedRuntime.hpp"
@@ -147,36 +148,50 @@
 #endif
 
   // Entry arguments:
-  //  rax: Interface
+  //  rax: CompiledICHolder
   //  j_rarg0: Receiver
 
-  // Free registers (non-args) are rax (interface), rbx
-
-  // get receiver (need to skip return address on top of stack)
-
-  assert(VtableStub::receiver_location() == j_rarg0->as_VMReg(), "receiver expected in j_rarg0");
-  // get receiver klass (also an implicit null-check)
-  address npe_addr = __ pc();
-
   // Most registers are in use; we'll use rax, rbx, r10, r11
   // (various calling sequences use r[cd]x, r[sd]i, r[89]; stay away from them)
-  __ load_klass(r10, j_rarg0);
+  const Register recv_klass_reg     = r10;
+  const Register holder_klass_reg   = rax; // declaring interface klass (DECC)
+  const Register resolved_klass_reg = rbx; // resolved interface klass (REFC)
+  const Register temp_reg           = r11;
+
+  Label L_no_such_interface;
+
+  const Register icholder_reg = rax;
+  __ movptr(resolved_klass_reg, Address(icholder_reg, CompiledICHolder::holder_klass_offset()));
+  __ movptr(holder_klass_reg,   Address(icholder_reg, CompiledICHolder::holder_metadata_offset()));
+
+  // get receiver klass (also an implicit null-check)
+  assert(VtableStub::receiver_location() == j_rarg0->as_VMReg(), "receiver expected in j_rarg0");
+  address npe_addr = __ pc();
+  __ load_klass(recv_klass_reg, j_rarg0);
+
+  // Receiver subtype check against REFC.
+  // Destroys recv_klass_reg value.
+  __ lookup_interface_method(// inputs: rec. class, interface
+                             recv_klass_reg, resolved_klass_reg, noreg,
+                             // outputs:  scan temp. reg1, scan temp. reg2
+                             recv_klass_reg, temp_reg,
+                             L_no_such_interface,
+                             /*return_method=*/false);
+
+  // Get selected method from declaring class and itable index
+  const Register method = rbx;
+  __ load_klass(recv_klass_reg, j_rarg0);   // restore recv_klass_reg
+  __ lookup_interface_method(// inputs: rec. class, interface, itable index
+                       recv_klass_reg, holder_klass_reg, itable_index,
+                       // outputs: method, scan temp. reg
+                       method, temp_reg,
+                       L_no_such_interface);
 
   // If we take a trap while this arg is on the stack we will not
   // be able to walk the stack properly. This is not an issue except
   // when there are mistakes in this assembly code that could generate
   // a spurious fault. Ask me how I know...
 
-  const Register method = rbx;
-  Label throw_icce;
-
-  // Get Method* and entrypoint for compiler
-  __ lookup_interface_method(// inputs: rec. class, interface, itable index
-                             r10, rax, itable_index,
-                             // outputs: method, scan temp. reg
-                             method, r11,
-                             throw_icce);
-
   // method (rbx): Method*
   // j_rarg0: receiver
 
@@ -197,7 +212,7 @@
   address ame_addr = __ pc();
   __ jmp(Address(method, Method::from_compiled_offset()));
 
-  __ bind(throw_icce);
+  __ bind(L_no_such_interface);
   __ jump(RuntimeAddress(StubRoutines::throw_IncompatibleClassChangeError_entry()));
 
   __ flush();
@@ -224,8 +239,8 @@
            (UseCompressedClassPointers ?  MacroAssembler::instr_size_for_decode_klass_not_null() : 0);
   } else {
     // Itable stub size
-    return (DebugVtables ? 512 : 74) + (CountCompiledCalls ? 13 : 0) +
-           (UseCompressedClassPointers ?  MacroAssembler::instr_size_for_decode_klass_not_null() : 0);
+    return (DebugVtables ? 512 : 140) + (CountCompiledCalls ? 13 : 0) +
+           (UseCompressedClassPointers ? 2 * MacroAssembler::instr_size_for_decode_klass_not_null() : 0);
   }
   // In order to tune these parameters, run the JVM with VM options
   // +PrintMiscellaneous and +WizardMode to see information about
--- a/src/hotspot/share/aot/aotCompiledMethod.cpp	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/hotspot/share/aot/aotCompiledMethod.cpp	Fri Jan 12 15:05:35 2018 -0800
@@ -270,7 +270,7 @@
         CompiledIC *ic = CompiledIC_at(&iter);
         if (ic->is_icholder_call()) {
           CompiledICHolder* cichk = ic->cached_icholder();
-          f(cichk->holder_method());
+          f(cichk->holder_metadata());
           f(cichk->holder_klass());
         } else {
           // Get Klass* or NULL (if value is -1) from GOT cell of virtual call PLT stub.
--- a/src/hotspot/share/code/compiledIC.cpp	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/hotspot/share/code/compiledIC.cpp	Fri Jan 12 15:05:35 2018 -0800
@@ -230,10 +230,13 @@
 #ifdef ASSERT
     int index = call_info->resolved_method()->itable_index();
     assert(index == itable_index, "CallInfo pre-computes this");
-#endif //ASSERT
     InstanceKlass* k = call_info->resolved_method()->method_holder();
     assert(k->verify_itable_index(itable_index), "sanity check");
-    InlineCacheBuffer::create_transition_stub(this, k, entry);
+#endif //ASSERT
+    CompiledICHolder* holder = new CompiledICHolder(call_info->resolved_method()->method_holder(),
+                                                    call_info->resolved_klass());
+    holder->claim();
+    InlineCacheBuffer::create_transition_stub(this, holder, entry);
   } else {
     assert(call_info->call_kind() == CallInfo::vtable_call, "either itable or vtable");
     // Can be different than selected_method->vtable_index(), due to package-private etc.
@@ -517,7 +520,14 @@
 
 bool CompiledIC::is_icholder_entry(address entry) {
   CodeBlob* cb = CodeCache::find_blob_unsafe(entry);
-  return (cb != NULL && cb->is_adapter_blob());
+  if (cb != NULL && cb->is_adapter_blob()) {
+    return true;
+  }
+  // itable stubs also use CompiledICHolder
+  if (VtableStubs::is_entry_point(entry) && VtableStubs::stub_containing(entry)->is_itable_stub()) {
+    return true;
+  }
+  return false;
 }
 
 bool CompiledIC::is_icholder_call_site(virtual_call_Relocation* call_site, const CompiledMethod* cm) {
--- a/src/hotspot/share/code/compiledIC.hpp	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/hotspot/share/code/compiledIC.hpp	Fri Jan 12 15:05:35 2018 -0800
@@ -45,11 +45,11 @@
 //          \                        /   \     /
 //       [4] \                      / [4] \->-/
 //            \->-  Megamorphic -<-/
-//                  (Method*)
+//              (CompiledICHolder*)
 //
-// The text in paranteses () refere to the value of the inline cache receiver (mov instruction)
+// The text in parentheses () refers to the value of the inline cache receiver (mov instruction)
 //
-// The numbers in square brackets refere to the kind of transition:
+// The numbers in square brackets refer to the kind of transition:
 // [1]: Initial fixup. Receiver it found from debug information
 // [2]: Compilation of a method
 // [3]: Recompilation of a method (note: only entry is changed. The Klass* must stay the same)
--- a/src/hotspot/share/code/compiledMethod.cpp	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/hotspot/share/code/compiledMethod.cpp	Fri Jan 12 15:05:35 2018 -0800
@@ -404,8 +404,7 @@
     // yet be marked below. (We check this further below).
     CompiledICHolder* cichk_oop = ic->cached_icholder();
 
-    if (cichk_oop->holder_method()->method_holder()->is_loader_alive(is_alive) &&
-        cichk_oop->holder_klass()->is_loader_alive(is_alive)) {
+    if (cichk_oop->is_loader_alive(is_alive)) {
       return;
     }
   } else {
--- a/src/hotspot/share/code/nmethod.cpp	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/hotspot/share/code/nmethod.cpp	Fri Jan 12 15:05:35 2018 -0800
@@ -1545,7 +1545,7 @@
         CompiledIC *ic = CompiledIC_at(&iter);
         if (ic->is_icholder_call()) {
           CompiledICHolder* cichk = ic->cached_icholder();
-          f(cichk->holder_method());
+          f(cichk->holder_metadata());
           f(cichk->holder_klass());
         } else {
           Metadata* ic_oop = ic->cached_metadata();
--- a/src/hotspot/share/interpreter/interpreterRuntime.cpp	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/hotspot/share/interpreter/interpreterRuntime.cpp	Fri Jan 12 15:05:35 2018 -0800
@@ -804,7 +804,7 @@
   // it is not an interface.  The receiver for invokespecial calls within interface
   // methods must be checked for every call.
   InstanceKlass* sender = pool->pool_holder();
-  sender = sender->is_anonymous() ? sender->host_klass() : sender;
+  sender = sender->has_host_klass() ? sender->host_klass() : sender;
 
   switch (info.call_kind()) {
   case CallInfo::direct_call:
@@ -822,6 +822,7 @@
   case CallInfo::itable_call:
     cp_cache_entry->set_itable_call(
       bytecode,
+      info.resolved_klass(),
       info.resolved_method(),
       info.itable_index());
     break;
--- a/src/hotspot/share/oops/compiledICHolder.cpp	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/hotspot/share/oops/compiledICHolder.cpp	Fri Jan 12 15:05:35 2018 -0800
@@ -32,8 +32,8 @@
 volatile int CompiledICHolder::_live_not_claimed_count;
 
 
-CompiledICHolder::CompiledICHolder(Method* method, Klass* klass)
-  : _holder_method(method), _holder_klass(klass) {
+CompiledICHolder::CompiledICHolder(Metadata* metadata, Klass* klass)
+  : _holder_metadata(metadata), _holder_klass(klass) {
 #ifdef ASSERT
   Atomic::inc(&_live_count);
   Atomic::inc(&_live_not_claimed_count);
@@ -47,12 +47,28 @@
 }
 #endif // ASSERT
 
+bool CompiledICHolder::is_loader_alive(BoolObjectClosure* is_alive) {
+  if (_holder_metadata->is_method()) {
+    if (!((Method*)_holder_metadata)->method_holder()->is_loader_alive(is_alive)) {
+      return false;
+    }
+  } else if (_holder_metadata->is_klass()) {
+    if (!((Klass*)_holder_metadata)->is_loader_alive(is_alive)) {
+      return false;
+    }
+  }
+  if (!_holder_klass->is_loader_alive(is_alive)) {
+    return false;
+  }
+  return true;
+}
+
 // Printing
 
 void CompiledICHolder::print_on(outputStream* st) const {
   st->print("%s", internal_name());
-  st->print(" - method: "); holder_method()->print_value_on(st); st->cr();
-  st->print(" - klass:  "); holder_klass()->print_value_on(st); st->cr();
+  st->print(" - metadata: "); holder_metadata()->print_value_on(st); st->cr();
+  st->print(" - klass:    "); holder_klass()->print_value_on(st); st->cr();
 }
 
 void CompiledICHolder::print_value_on(outputStream* st) const {
@@ -63,7 +79,7 @@
 // Verification
 
 void CompiledICHolder::verify_on(outputStream* st) {
-  guarantee(holder_method()->is_method(), "should be method");
+  guarantee(holder_metadata()->is_method() || holder_metadata()->is_klass(), "should be method or klass");
   guarantee(holder_klass()->is_klass(),   "should be klass");
 }
 
--- a/src/hotspot/share/oops/compiledICHolder.hpp	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/hotspot/share/oops/compiledICHolder.hpp	Fri Jan 12 15:05:35 2018 -0800
@@ -29,8 +29,9 @@
 #include "utilities/macros.hpp"
 
 // A CompiledICHolder* is a helper object for the inline cache implementation.
-// It holds an intermediate value (method+klass pair) used when converting from
-// compiled to an interpreted call.
+// It holds:
+//   (1) (method+klass pair) when converting from compiled to an interpreted call
+//   (2) (klass+klass pair) when calling itable stub from megamorphic compiled call
 //
 // These are always allocated in the C heap and are freed during a
 // safepoint by the ICBuffer logic.  It's unsafe to free them earlier
@@ -45,32 +46,33 @@
   static volatile int _live_not_claimed_count; // allocated but not yet in use so not
                                                // reachable by iterating over nmethods
 
-  Method* _holder_method;
+  Metadata* _holder_metadata;
   Klass*    _holder_klass;    // to avoid name conflict with oopDesc::_klass
   CompiledICHolder* _next;
 
  public:
   // Constructor
-  CompiledICHolder(Method* method, Klass* klass);
+  CompiledICHolder(Metadata* metadata, Klass* klass);
   ~CompiledICHolder() NOT_DEBUG_RETURN;
 
   static int live_count() { return _live_count; }
   static int live_not_claimed_count() { return _live_not_claimed_count; }
 
   // accessors
-  Method* holder_method() const     { return _holder_method; }
   Klass*    holder_klass()  const     { return _holder_klass; }
+  Metadata* holder_metadata() const   { return _holder_metadata; }
 
-  void set_holder_method(Method* m) { _holder_method = m; }
-  void set_holder_klass(Klass* k)   { _holder_klass = k; }
+  void set_holder_metadata(Metadata* m) { _holder_metadata = m; }
+  void set_holder_klass(Klass* k)     { _holder_klass = k; }
 
-  // interpreter support (offsets in bytes)
-  static int holder_method_offset()   { return offset_of(CompiledICHolder, _holder_method); }
+  static int holder_metadata_offset() { return offset_of(CompiledICHolder, _holder_metadata); }
   static int holder_klass_offset()    { return offset_of(CompiledICHolder, _holder_klass); }
 
   CompiledICHolder* next()     { return _next; }
   void set_next(CompiledICHolder* n) { _next = n; }
 
+  bool is_loader_alive(BoolObjectClosure* is_alive);
+
   // Verify
   void verify_on(outputStream* st);
 
--- a/src/hotspot/share/oops/constantPool.hpp	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/hotspot/share/oops/constantPool.hpp	Fri Jan 12 15:05:35 2018 -0800
@@ -25,6 +25,7 @@
 #ifndef SHARE_VM_OOPS_CONSTANTPOOLOOP_HPP
 #define SHARE_VM_OOPS_CONSTANTPOOLOOP_HPP
 
+#include "memory/allocation.inline.hpp"
 #include "oops/arrayOop.hpp"
 #include "oops/cpCache.hpp"
 #include "oops/objArrayOop.hpp"
@@ -1021,7 +1022,7 @@
         delete(cur);
       }
     }
-    delete _buckets;
+    FREE_C_HEAP_ARRAY(SymbolHashMapBucket, _buckets);
   }
 }; // End SymbolHashMap class
 
--- a/src/hotspot/share/oops/cpCache.cpp	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/hotspot/share/oops/cpCache.cpp	Fri Jan 12 15:05:35 2018 -0800
@@ -277,14 +277,16 @@
   set_direct_or_vtable_call(invoke_code, method, index, false);
 }
 
-void ConstantPoolCacheEntry::set_itable_call(Bytecodes::Code invoke_code, const methodHandle& method, int index) {
+void ConstantPoolCacheEntry::set_itable_call(Bytecodes::Code invoke_code,
+                                             Klass* referenced_klass,
+                                             const methodHandle& method, int index) {
   assert(method->method_holder()->verify_itable_index(index), "");
   assert(invoke_code == Bytecodes::_invokeinterface, "");
   InstanceKlass* interf = method->method_holder();
   assert(interf->is_interface(), "must be an interface");
   assert(!method->is_final_method(), "interfaces do not have final methods; cannot link to one here");
-  set_f1(interf);
-  set_f2(index);
+  set_f1(referenced_klass);
+  set_f2((intx)method());
   set_method_flags(as_TosState(method->result_type()),
                    0,  // no option bits
                    method()->size_of_parameters());
@@ -513,10 +515,23 @@
 
 
 #if INCLUDE_JVMTI
+
+void log_adjust(const char* entry_type, Method* old_method, Method* new_method, bool* trace_name_printed) {
+  if (log_is_enabled(Info, redefine, class, update)) {
+    ResourceMark rm;
+    if (!(*trace_name_printed)) {
+      log_info(redefine, class, update)("adjust: name=%s", old_method->method_holder()->external_name());
+      *trace_name_printed = true;
+    }
+    log_debug(redefine, class, update, constantpool)
+          ("cpc %s entry update: %s(%s)", entry_type, new_method->name()->as_C_string(), new_method->signature()->as_C_string());
+  }
+}
+
 // RedefineClasses() API support:
 // If this ConstantPoolCacheEntry refers to old_method then update it
 // to refer to new_method.
-bool ConstantPoolCacheEntry::adjust_method_entry(Method* old_method,
+void ConstantPoolCacheEntry::adjust_method_entry(Method* old_method,
        Method* new_method, bool * trace_name_printed) {
 
   if (is_vfinal()) {
@@ -525,63 +540,35 @@
       // match old_method so need an update
       // NOTE: can't use set_f2_as_vfinal_method as it asserts on different values
       _f2 = (intptr_t)new_method;
-      if (log_is_enabled(Info, redefine, class, update)) {
-        ResourceMark rm;
-        if (!(*trace_name_printed)) {
-          log_info(redefine, class, update)("adjust: name=%s", old_method->method_holder()->external_name());
-          *trace_name_printed = true;
-        }
-        log_debug(redefine, class, update, constantpool)
-          ("cpc vf-entry update: %s(%s)", new_method->name()->as_C_string(), new_method->signature()->as_C_string());
-      }
-      return true;
+      log_adjust("vfinal", old_method, new_method, trace_name_printed);
     }
-
-    // f1() is not used with virtual entries so bail out
-    return false;
+    return;
   }
 
-  if (_f1 == NULL) {
-    // NULL f1() means this is a virtual entry so bail out
-    // We are assuming that the vtable index does not need change.
-    return false;
-  }
+  assert (_f1 != NULL, "should not call with uninteresting entry");
 
-  if (_f1 == old_method) {
+  if (!(_f1->is_method())) {
+    // _f1 is a Klass* for an interface, _f2 is the method
+    if (f2_as_interface_method() == old_method) {
+      _f2 = (intptr_t)new_method;
+      log_adjust("interface", old_method, new_method, trace_name_printed);
+    }
+  } else if (_f1 == old_method) {
     _f1 = new_method;
-    if (log_is_enabled(Info, redefine, class, update)) {
-      ResourceMark rm;
-      if (!(*trace_name_printed)) {
-        log_info(redefine, class, update)("adjust: name=%s", old_method->method_holder()->external_name());
-        *trace_name_printed = true;
-      }
-      log_debug(redefine, class, update, constantpool)
-        ("cpc entry update: %s(%s)", new_method->name()->as_C_string(), new_method->signature()->as_C_string());
-    }
-    return true;
+    log_adjust("special, static or dynamic", old_method, new_method, trace_name_printed);
   }
-
-  return false;
 }
 
 // a constant pool cache entry should never contain old or obsolete methods
 bool ConstantPoolCacheEntry::check_no_old_or_obsolete_entries() {
-  if (is_vfinal()) {
-    // virtual and final so _f2 contains method ptr instead of vtable index
-    Metadata* f2 = (Metadata*)_f2;
-    // Return false if _f2 refers to an old or an obsolete method.
-    // _f2 == NULL || !_f2->is_method() are just as unexpected here.
-    return (f2 != NULL NOT_PRODUCT(&& f2->is_valid()) && f2->is_method() &&
-            !((Method*)f2)->is_old() && !((Method*)f2)->is_obsolete());
-  } else if (_f1 == NULL ||
-             (NOT_PRODUCT(_f1->is_valid() &&) !_f1->is_method())) {
-    // _f1 == NULL || !_f1->is_method() are OK here
+  Method* m = get_interesting_method_entry(NULL);
+  // return false if m refers to a non-deleted old or obsolete method
+  if (m != NULL) {
+    assert(m->is_valid() && m->is_method(), "m is a valid method");
+    return !m->is_old() && !m->is_obsolete(); // old is always set for old and obsolete
+  } else {
     return true;
   }
-  // return false if _f1 refers to a non-deleted old or obsolete method
-  return (NOT_PRODUCT(_f1->is_valid() &&) _f1->is_method() &&
-          (f1_as_method()->is_deleted() ||
-          (!f1_as_method()->is_old() && !f1_as_method()->is_obsolete())));
 }
 
 Method* ConstantPoolCacheEntry::get_interesting_method_entry(Klass* k) {
@@ -598,10 +585,11 @@
     return NULL;
   } else {
     if (!(_f1->is_method())) {
-      // _f1 can also contain a Klass* for an interface
-      return NULL;
+      // _f1 is a Klass* for an interface
+      m = f2_as_interface_method();
+    } else {
+      m = f1_as_method();
     }
-    m = f1_as_method();
   }
   assert(m != NULL && m->is_method(), "sanity check");
   if (m == NULL || !m->is_method() || (k != NULL && m->method_holder() != k)) {
--- a/src/hotspot/share/oops/cpCache.hpp	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/hotspot/share/oops/cpCache.hpp	Fri Jan 12 15:05:35 2018 -0800
@@ -249,6 +249,7 @@
 
   void set_itable_call(
     Bytecodes::Code invoke_code,                 // the bytecode used; must be invokeinterface
+    Klass* referenced_klass,                     // the referenced klass in the InterfaceMethodref
     const methodHandle& method,                  // the resolved interface method
     int itable_index                             // index into itable for the method
   );
@@ -352,6 +353,7 @@
   bool      is_f1_null() const                   { Metadata* f1 = f1_ord(); return f1 == NULL; }  // classifies a CPC entry as unbound
   int       f2_as_index() const                  { assert(!is_vfinal(), ""); return (int) _f2; }
   Method*   f2_as_vfinal_method() const          { assert(is_vfinal(), ""); return (Method*)_f2; }
+  Method*   f2_as_interface_method() const       { assert(bytecode_1() == Bytecodes::_invokeinterface, ""); return (Method*)_f2; }
   intx flags_ord() const                         { return (intx)OrderAccess::load_acquire(&_flags); }
   int  field_index() const                       { assert(is_field_entry(),  ""); return (_flags & field_index_mask); }
   int  parameter_size() const                    { assert(is_method_entry(), ""); return (_flags & parameter_size_mask); }
@@ -387,7 +389,7 @@
   // trace_name_printed is set to true if the current call has
   // printed the klass name so that other routines in the adjust_*
   // group don't print the klass name.
-  bool adjust_method_entry(Method* old_method, Method* new_method,
+  void adjust_method_entry(Method* old_method, Method* new_method,
          bool* trace_name_printed);
   bool check_no_old_or_obsolete_entries();
   Method* get_interesting_method_entry(Klass* k);
--- a/src/hotspot/share/oops/instanceKlass.hpp	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/hotspot/share/oops/instanceKlass.hpp	Fri Jan 12 15:05:35 2018 -0800
@@ -609,9 +609,11 @@
   InstanceKlass* host_klass() const              {
     InstanceKlass** hk = adr_host_klass();
     if (hk == NULL) {
+      assert(!is_anonymous(), "Anonymous classes have host klasses");
       return NULL;
     } else {
       assert(*hk != NULL, "host klass should always be set if the address is not null");
+      assert(is_anonymous(), "Only anonymous classes have host klasses");
       return *hk;
     }
   }
@@ -623,6 +625,9 @@
       *addr = host;
     }
   }
+  bool has_host_klass() const              {
+    return adr_host_klass() != NULL;
+  }
   bool is_anonymous() const                {
     return (_misc_flags & _misc_is_anonymous) != 0;
   }
--- a/src/hotspot/share/oops/klassVtable.cpp	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/hotspot/share/oops/klassVtable.cpp	Fri Jan 12 15:05:35 2018 -0800
@@ -1185,7 +1185,6 @@
   Array<Method*>* methods = InstanceKlass::cast(interf)->methods();
   int nof_methods = methods->length();
   HandleMark hm;
-  assert(nof_methods > 0, "at least one method must exist for interface to be in vtable");
   Handle interface_loader (THREAD, InstanceKlass::cast(interf)->class_loader());
 
   int ime_count = method_count_for_interface(interf);
@@ -1354,8 +1353,10 @@
       }
     }
 
-    // Only count interfaces with at least one method
-    if (method_count > 0) {
+    // Visit all interfaces which either have any methods or can participate in receiver type check.
+    // We do not bother to count methods in transitive interfaces, although that would allow us to skip
+    // this step in the rare case of a zero-method interface extending another zero-method interface.
+    if (method_count > 0 || InstanceKlass::cast(intf)->transitive_interfaces()->length() > 0) {
       blk->doit(intf, method_count);
     }
   }
--- a/src/hotspot/share/oops/method.hpp	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/hotspot/share/oops/method.hpp	Fri Jan 12 15:05:35 2018 -0800
@@ -698,6 +698,7 @@
   static ByteSize from_interpreted_offset()      { return byte_offset_of(Method, _from_interpreted_entry ); }
   static ByteSize interpreter_entry_offset()     { return byte_offset_of(Method, _i2i_entry ); }
   static ByteSize signature_handler_offset()     { return in_ByteSize(sizeof(Method) + wordSize);      }
+  static ByteSize itable_index_offset()          { return byte_offset_of(Method, _vtable_index ); }
 
   // for code generation
   static int method_data_offset_in_bytes()       { return offset_of(Method, _method_data); }
--- a/src/hotspot/share/prims/jni.cpp	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/hotspot/share/prims/jni.cpp	Fri Jan 12 15:05:35 2018 -0800
@@ -2820,7 +2820,7 @@
   EntryProbe; \
   DT_VOID_RETURN_MARK(Get##Result##ArrayRegion); \
   typeArrayOop src = typeArrayOop(JNIHandles::resolve_non_null(array)); \
-  if (start < 0 || len < 0 || ((unsigned int)start + (unsigned int)len > (unsigned int)src->length())) { \
+  if (start < 0 || len < 0 || (start > src->length() - len)) { \
     THROW(vmSymbols::java_lang_ArrayIndexOutOfBoundsException()); \
   } else { \
     if (len > 0) { \
@@ -2870,7 +2870,7 @@
   EntryProbe; \
   DT_VOID_RETURN_MARK(Set##Result##ArrayRegion); \
   typeArrayOop dst = typeArrayOop(JNIHandles::resolve_non_null(array)); \
-  if (start < 0 || len < 0 || ((unsigned int)start + (unsigned int)len > (unsigned int)dst->length())) { \
+  if (start < 0 || len < 0 || (start > dst->length() - len)) { \
     THROW(vmSymbols::java_lang_ArrayIndexOutOfBoundsException()); \
   } else { \
     if (len > 0) { \
@@ -3106,7 +3106,7 @@
   DT_VOID_RETURN_MARK(GetStringRegion);
   oop s = JNIHandles::resolve_non_null(string);
   int s_len = java_lang_String::length(s);
-  if (start < 0 || len < 0 || start + len > s_len) {
+  if (start < 0 || len < 0 || start > s_len - len) {
     THROW(vmSymbols::java_lang_StringIndexOutOfBoundsException());
   } else {
     if (len > 0) {
@@ -3132,7 +3132,7 @@
   DT_VOID_RETURN_MARK(GetStringUTFRegion);
   oop s = JNIHandles::resolve_non_null(string);
   int s_len = java_lang_String::length(s);
-  if (start < 0 || len < 0 || start + len > s_len) {
+  if (start < 0 || len < 0 || start > s_len - len) {
     THROW(vmSymbols::java_lang_StringIndexOutOfBoundsException());
   } else {
     //%note jni_7
--- a/src/hotspot/share/runtime/vmStructs.cpp	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/hotspot/share/runtime/vmStructs.cpp	Fri Jan 12 15:05:35 2018 -0800
@@ -233,7 +233,7 @@
   nonstatic_field(ArrayKlass,                  _dimension,                                    int)                                   \
   volatile_nonstatic_field(ArrayKlass,         _higher_dimension,                             Klass*)                                \
   volatile_nonstatic_field(ArrayKlass,         _lower_dimension,                              Klass*)                                \
-  nonstatic_field(CompiledICHolder,            _holder_method,                                Method*)                               \
+  nonstatic_field(CompiledICHolder,            _holder_metadata,                              Metadata*)                               \
   nonstatic_field(CompiledICHolder,            _holder_klass,                                 Klass*)                                \
   nonstatic_field(ConstantPool,                _tags,                                         Array<u1>*)                            \
   nonstatic_field(ConstantPool,                _cache,                                        ConstantPoolCache*)                    \
--- a/src/java.base/macosx/native/libosxsecurity/KeystoreImpl.m	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.base/macosx/native/libosxsecurity/KeystoreImpl.m	Fri Jan 12 15:05:35 2018 -0800
@@ -439,6 +439,11 @@
                 goto errOut;
             }
             passwordStrRef = CFStringCreateWithCharacters(kCFAllocatorDefault, passwordChars, passwordLen);
+
+            // clear the password and release
+            memset(passwordChars, 0, passwordLen);
+            (*env)->ReleaseCharArrayElements(env, passwordObj, passwordChars,
+                JNI_ABORT);
         }
     }
 
@@ -527,8 +532,19 @@
 
     if (passwordObj) {
         passwordLen = (*env)->GetArrayLength(env, passwordObj);
-        passwordChars = (*env)->GetCharArrayElements(env, passwordObj, NULL);
-        passwordStrRef = CFStringCreateWithCharacters(kCFAllocatorDefault, passwordChars, passwordLen);
+
+        if (passwordLen > 0) {
+            passwordChars = (*env)->GetCharArrayElements(env, passwordObj, NULL);
+            if (passwordChars == NULL) {
+                goto errOut;
+            }
+            passwordStrRef = CFStringCreateWithCharacters(kCFAllocatorDefault, passwordChars, passwordLen);
+
+            // clear the password and release
+            memset(passwordChars, 0, passwordLen);
+            (*env)->ReleaseCharArrayElements(env, passwordObj, passwordChars,
+                JNI_ABORT);
+        }
     }
 
     paramBlock.version = SEC_KEY_IMPORT_EXPORT_PARAMS_VERSION;
--- a/src/java.base/share/classes/com/sun/crypto/provider/DESKey.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.base/share/classes/com/sun/crypto/provider/DESKey.java	Fri Jan 12 15:05:35 2018 -0800
@@ -25,6 +25,7 @@
 
 package com.sun.crypto.provider;
 
+import java.lang.ref.Reference;
 import java.security.MessageDigest;
 import java.security.KeyRep;
 import java.security.InvalidKeyException;
@@ -86,7 +87,12 @@
     public byte[] getEncoded() {
         // Return a copy of the key, rather than a reference,
         // so that the key data cannot be modified from outside
-        return this.key.clone();
+
+        // The key is zeroized by finalize()
+        // The reachability fence ensures finalize() isn't called early
+        byte[] result = key.clone();
+        Reference.reachabilityFence(this);
+        return result;
     }
 
     public String getAlgorithm() {
--- a/src/java.base/share/classes/com/sun/crypto/provider/DESedeKey.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.base/share/classes/com/sun/crypto/provider/DESedeKey.java	Fri Jan 12 15:05:35 2018 -0800
@@ -25,6 +25,7 @@
 
 package com.sun.crypto.provider;
 
+import java.lang.ref.Reference;
 import java.security.MessageDigest;
 import java.security.KeyRep;
 import java.security.InvalidKeyException;
@@ -86,7 +87,11 @@
     }
 
     public byte[] getEncoded() {
-        return this.key.clone();
+        // The key is zeroized by finalize()
+        // The reachability fence ensures finalize() isn't called early
+        byte[] result = key.clone();
+        Reference.reachabilityFence(this);
+        return result;
     }
 
     public String getAlgorithm() {
--- a/src/java.base/share/classes/com/sun/crypto/provider/DHKeyAgreement.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.base/share/classes/com/sun/crypto/provider/DHKeyAgreement.java	Fri Jan 12 15:05:35 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -28,11 +28,13 @@
 import java.util.*;
 import java.lang.*;
 import java.math.BigInteger;
+import java.security.AccessController;
 import java.security.InvalidAlgorithmParameterException;
 import java.security.InvalidKeyException;
 import java.security.Key;
 import java.security.NoSuchAlgorithmException;
 import java.security.SecureRandom;
+import java.security.PrivilegedAction;
 import java.security.ProviderException;
 import java.security.spec.AlgorithmParameterSpec;
 import java.security.spec.InvalidKeySpecException;
@@ -60,6 +62,17 @@
     private BigInteger x = BigInteger.ZERO; // the private value
     private BigInteger y = BigInteger.ZERO;
 
+    private static class AllowKDF {
+
+        private static final boolean VALUE = getValue();
+
+        private static boolean getValue() {
+            return AccessController.doPrivileged(
+                (PrivilegedAction<Boolean>)
+                () -> Boolean.getBoolean("jdk.crypto.KeyAgreement.legacyKDF"));
+        }
+    }
+
     /**
      * Empty constructor
      */
@@ -367,6 +380,14 @@
         if (algorithm == null) {
             throw new NoSuchAlgorithmException("null algorithm");
         }
+
+        if (!algorithm.equalsIgnoreCase("TlsPremasterSecret") &&
+            !AllowKDF.VALUE) {
+
+            throw new NoSuchAlgorithmException("Unsupported secret key "
+                                               + "algorithm: " + algorithm);
+        }
+
         byte[] secret = engineGenerateSecret();
         if (algorithm.equalsIgnoreCase("DES")) {
             // DES
--- a/src/java.base/share/classes/com/sun/crypto/provider/PBEKey.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.base/share/classes/com/sun/crypto/provider/PBEKey.java	Fri Jan 12 15:05:35 2018 -0800
@@ -25,6 +25,7 @@
 
 package com.sun.crypto.provider;
 
+import java.lang.ref.Reference;
 import java.security.MessageDigest;
 import java.security.KeyRep;
 import java.security.spec.InvalidKeySpecException;
@@ -80,7 +81,11 @@
     }
 
     public byte[] getEncoded() {
-        return this.key.clone();
+        // The key is zeroized by finalize()
+        // The reachability fence ensures finalize() isn't called early
+        byte[] result = key.clone();
+        Reference.reachabilityFence(this);
+        return result;
     }
 
     public String getAlgorithm() {
--- a/src/java.base/share/classes/com/sun/crypto/provider/PBKDF2KeyImpl.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.base/share/classes/com/sun/crypto/provider/PBKDF2KeyImpl.java	Fri Jan 12 15:05:35 2018 -0800
@@ -26,6 +26,7 @@
 package com.sun.crypto.provider;
 
 import java.io.ObjectStreamException;
+import java.lang.ref.Reference;
 import java.nio.ByteBuffer;
 import java.nio.CharBuffer;
 import java.nio.charset.Charset;
@@ -208,7 +209,11 @@
     }
 
     public byte[] getEncoded() {
-        return key.clone();
+        // The key is zeroized by finalize()
+        // The reachability fence ensures finalize() isn't called early
+        byte[] result = key.clone();
+        Reference.reachabilityFence(this);
+        return result;
     }
 
     public String getAlgorithm() {
@@ -220,7 +225,11 @@
     }
 
     public char[] getPassword() {
-        return passwd.clone();
+        // The password is zeroized by finalize()
+        // The reachability fence ensures finalize() isn't called early
+        char[] result = passwd.clone();
+        Reference.reachabilityFence(this);
+        return result;
     }
 
     public byte[] getSalt() {
--- a/src/java.base/share/classes/java/lang/invoke/DirectMethodHandle.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.base/share/classes/java/lang/invoke/DirectMethodHandle.java	Fri Jan 12 15:05:35 2018 -0800
@@ -80,13 +80,20 @@
             mtype = mtype.insertParameterTypes(0, receiver);
         }
         if (!member.isField()) {
-            if (refKind == REF_invokeSpecial) {
-                member = member.asSpecial();
-                LambdaForm lform = preparedLambdaForm(member);
-                return new Special(mtype, lform, member);
-            } else {
-                LambdaForm lform = preparedLambdaForm(member);
-                return new DirectMethodHandle(mtype, lform, member);
+            switch (refKind) {
+                case REF_invokeSpecial: {
+                    member = member.asSpecial();
+                    LambdaForm lform = preparedLambdaForm(member);
+                    return new Special(mtype, lform, member);
+                }
+                case REF_invokeInterface: {
+                    LambdaForm lform = preparedLambdaForm(member);
+                    return new Interface(mtype, lform, member, receiver);
+                }
+                default: {
+                    LambdaForm lform = preparedLambdaForm(member);
+                    return new DirectMethodHandle(mtype, lform, member);
+                }
             }
         } else {
             LambdaForm lform = preparedFieldLambdaForm(member);
@@ -190,6 +197,7 @@
     static LambdaForm makePreparedLambdaForm(MethodType mtype, int which) {
         boolean needsInit = (which == LF_INVSTATIC_INIT);
         boolean doesAlloc = (which == LF_NEWINVSPECIAL);
+        boolean needsReceiverCheck = (which == LF_INVINTERFACE);
         String linkerName;
         LambdaForm.Kind kind;
         switch (which) {
@@ -219,6 +227,7 @@
         int nameCursor = ARG_LIMIT;
         final int NEW_OBJ     = (doesAlloc ? nameCursor++ : -1);
         final int GET_MEMBER  = nameCursor++;
+        final int CHECK_RECEIVER = (needsReceiverCheck ? nameCursor++ : -1);
         final int LINKER_CALL = nameCursor++;
         Name[] names = arguments(nameCursor - ARG_LIMIT, mtype.invokerType());
         assert(names.length == nameCursor);
@@ -233,6 +242,10 @@
         }
         assert(findDirectMethodHandle(names[GET_MEMBER]) == names[DMH_THIS]);
         Object[] outArgs = Arrays.copyOfRange(names, ARG_BASE, GET_MEMBER+1, Object[].class);
+        if (needsReceiverCheck) {
+            names[CHECK_RECEIVER] = new Name(getFunction(NF_checkReceiver), names[DMH_THIS], names[ARG_BASE]);
+            outArgs[0] = names[CHECK_RECEIVER];
+        }
         assert(outArgs[outArgs.length-1] == names[GET_MEMBER]);  // look, shifted args!
         int result = LAST_RESULT;
         if (doesAlloc) {
@@ -376,6 +389,29 @@
         }
     }
 
+    /** This subclass represents invokeinterface instructions. */
+    static class Interface extends DirectMethodHandle {
+        private final Class<?> refc;
+        private Interface(MethodType mtype, LambdaForm form, MemberName member, Class<?> refc) {
+            super(mtype, form, member);
+            assert refc.isInterface() : refc;
+            this.refc = refc;
+        }
+        @Override
+        MethodHandle copyWith(MethodType mt, LambdaForm lf) {
+            return new Interface(mt, lf, member, refc);
+        }
+
+        Object checkReceiver(Object recv) {
+            if (!refc.isInstance(recv)) {
+                String msg = String.format("Class %s does not implement the requested interface %s",
+                        recv.getClass().getName(), refc.getName());
+                throw new IncompatibleClassChangeError(msg);
+            }
+            return recv;
+        }
+    }
+
     /** This subclass handles constructor references. */
     static class Constructor extends DirectMethodHandle {
         final MemberName initMethod;
@@ -738,7 +774,8 @@
             NF_allocateInstance = 8,
             NF_constructorMethod = 9,
             NF_UNSAFE = 10,
-            NF_LIMIT = 11;
+            NF_checkReceiver = 11,
+            NF_LIMIT = 12;
 
     private static final @Stable NamedFunction[] NFS = new NamedFunction[NF_LIMIT];
 
@@ -785,6 +822,11 @@
                     return new NamedFunction(
                             MemberName.getFactory()
                                     .resolveOrFail(REF_getField, member, DirectMethodHandle.class, NoSuchMethodException.class));
+                case NF_checkReceiver:
+                    member = new MemberName(Interface.class, "checkReceiver", OBJ_OBJ_TYPE, REF_invokeVirtual);
+                    return new NamedFunction(
+                        MemberName.getFactory()
+                            .resolveOrFail(REF_invokeVirtual, member, Interface.class, NoSuchMethodException.class));
                 default:
                     throw newInternalError("Unknown function: " + func);
             }
--- a/src/java.base/share/classes/java/util/ResourceBundle.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.base/share/classes/java/util/ResourceBundle.java	Fri Jan 12 15:05:35 2018 -0800
@@ -571,7 +571,7 @@
      */
     private static ClassLoader getLoaderForControl(Module module) {
         ClassLoader loader = getLoader(module);
-        return loader == null ? ClassLoader.getSystemClassLoader() : loader;
+        return loader == null ? ClassLoader.getPlatformClassLoader() : loader;
     }
 
     /**
--- a/src/java.base/share/classes/java/util/concurrent/ArrayBlockingQueue.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.base/share/classes/java/util/concurrent/ArrayBlockingQueue.java	Fri Jan 12 15:05:35 2018 -0800
@@ -1608,4 +1608,30 @@
         }
     }
 
+    /**
+     * Deserializes this queue and then checks some invariants.
+     *
+     * @param s the input stream
+     * @throws ClassNotFoundException if the class of a serialized object
+     *         could not be found
+     * @throws java.io.InvalidObjectException if invariants are violated
+     * @throws java.io.IOException if an I/O error occurs
+     */
+    private void readObject(java.io.ObjectInputStream s)
+        throws java.io.IOException, ClassNotFoundException {
+
+        // Read in items array and various fields
+        s.defaultReadObject();
+
+        // Check invariants over count and index fields. Note that
+        // if putIndex==takeIndex, count can be either 0 or items.length.
+        if (items.length == 0 ||
+            takeIndex < 0 || takeIndex >= items.length ||
+            putIndex  < 0 || putIndex  >= items.length ||
+            count < 0     || count     >  items.length ||
+            Math.floorMod(putIndex - takeIndex, items.length) !=
+            Math.floorMod(count, items.length)) {
+            throw new java.io.InvalidObjectException("invariants violated");
+        }
+    }
 }
--- a/src/java.base/share/classes/module-info.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.base/share/classes/module-info.java	Fri Jan 12 15:05:35 2018 -0800
@@ -212,7 +212,8 @@
     exports jdk.internal.util.jar to
         jdk.jartool;
     exports sun.net to
-        jdk.incubator.httpclient;
+        jdk.incubator.httpclient,
+        jdk.naming.dns;
     exports sun.net.ext to
         jdk.net;
     exports sun.net.dns to
--- a/src/java.base/share/classes/sun/security/rsa/RSAPublicKeyImpl.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.base/share/classes/sun/security/rsa/RSAPublicKeyImpl.java	Fri Jan 12 15:05:35 2018 -0800
@@ -48,6 +48,7 @@
 public final class RSAPublicKeyImpl extends X509Key implements RSAPublicKey {
 
     private static final long serialVersionUID = 2644735423591199609L;
+    private static final BigInteger THREE = BigInteger.valueOf(3);
 
     private BigInteger n;       // modulus
     private BigInteger e;       // public exponent
@@ -61,6 +62,7 @@
         this.n = n;
         this.e = e;
         RSAKeyFactory.checkRSAProviderKeyLengths(n.bitLength(), e);
+        checkExponentRange();
         // generate the encoding
         algid = RSAPrivateCrtKeyImpl.rsaId;
         try {
@@ -83,6 +85,19 @@
     public RSAPublicKeyImpl(byte[] encoded) throws InvalidKeyException {
         decode(encoded);
         RSAKeyFactory.checkRSAProviderKeyLengths(n.bitLength(), e);
+        checkExponentRange();
+    }
+
+    private void checkExponentRange() throws InvalidKeyException {
+        // the exponent should be smaller than the modulus
+        if (e.compareTo(n) >= 0) {
+            throw new InvalidKeyException("exponent is larger than modulus");
+        }
+
+        // the exponent should be at least 3
+        if (e.compareTo(THREE) < 0) {
+            throw new InvalidKeyException("exponent is smaller than 3");
+        }
     }
 
     // see JCA doc
--- a/src/java.base/share/classes/sun/security/ssl/HandshakeHash.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.base/share/classes/sun/security/ssl/HandshakeHash.java	Fri Jan 12 15:05:35 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -108,7 +108,29 @@
      * a hash for the certificate verify message is required.
      */
     HandshakeHash(boolean needCertificateVerify) {
-        clonesNeeded = needCertificateVerify ? 4 : 3;
+        // We may rework the code later, but for now we use hard-coded number
+        // of clones if the underlying MessageDigests are not cloneable.
+        //
+        // The number used here is based on the current handshake protocols and
+        // implementation.  It may be changed if the handshake processe gets
+        // changed in the future, for example adding a new extension that
+        // requires handshake hash.  Please be careful about the number of
+        // clones if additional handshak hash is required in the future.
+        //
+        // For the current implementation, the handshake hash is required for
+        // the following items:
+        //     . CertificateVerify handshake message (optional)
+        //     . client Finished handshake message
+        //     . server Finished Handshake message
+        //     . the extended Master Secret extension [RFC 7627]
+        //
+        // Note that a late call to server setNeedClientAuth dose not update
+        // the number of clones.  We may address the issue later.
+        //
+        // Note for safety, we allocate one more clone for the current
+        // implementation.  We may consider it more carefully in the future
+        // for the exact number or rework the code in a different way.
+        clonesNeeded = needCertificateVerify ? 5 : 4;
     }
 
     void reserve(ByteBuffer input) {
@@ -335,7 +357,8 @@
         if (finMD != null) return;
 
         try {
-            finMD = CloneableDigest.getDigest(normalizeAlgName(s), 2);
+            // See comment in the contructor.
+            finMD = CloneableDigest.getDigest(normalizeAlgName(s), 4);
         } catch (NoSuchAlgorithmException e) {
             throw new Error(e);
         }
--- a/src/java.base/share/classes/sun/security/tools/keytool/Main.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.base/share/classes/sun/security/tools/keytool/Main.java	Fri Jan 12 15:05:35 2018 -0800
@@ -1804,8 +1804,7 @@
             } else if ("RSA".equalsIgnoreCase(keyAlgName)) {
                 keysize = SecurityProviderConstants.DEF_RSA_KEY_SIZE;
             } else if ("DSA".equalsIgnoreCase(keyAlgName)) {
-                // hardcode for now as DEF_DSA_KEY_SIZE is still 1024
-                keysize = 2048; // SecurityProviderConstants.DEF_DSA_KEY_SIZE;
+                keysize = SecurityProviderConstants.DEF_DSA_KEY_SIZE;
             }
         }
 
--- a/src/java.base/share/classes/sun/security/util/DerValue.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.base/share/classes/sun/security/util/DerValue.java	Fri Jan 12 15:05:35 2018 -0800
@@ -490,20 +490,27 @@
      * @return the octet string held in this DER value
      */
     public byte[] getOctetString() throws IOException {
-        byte[] bytes;
 
         if (tag != tag_OctetString && !isConstructed(tag_OctetString)) {
             throw new IOException(
                 "DerValue.getOctetString, not an Octet String: " + tag);
         }
-        bytes = new byte[length];
-        // Note: do not tempt to call buffer.read(bytes) at all. There's a
+        // Note: do not attempt to call buffer.read(bytes) at all. There's a
         // known bug that it returns -1 instead of 0.
         if (length == 0) {
-            return bytes;
+            return new byte[0];
         }
-        if (buffer.read(bytes) != length)
+
+        // Only allocate the array if there are enough bytes available.
+        // This only works for ByteArrayInputStream.
+        // The assignment below ensures that buffer has the required type.
+        ByteArrayInputStream arrayInput = buffer;
+        if (arrayInput.available() < length) {
             throw new IOException("short read on DerValue buffer");
+        }
+        byte[] bytes = new byte[length];
+        arrayInput.read(bytes);
+
         if (isConstructed()) {
             DerInputStream in = new DerInputStream(bytes, 0, bytes.length,
                 buffer.allowBER);
--- a/src/java.base/share/classes/sun/security/util/SecurityProviderConstants.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.base/share/classes/sun/security/util/SecurityProviderConstants.java	Fri Jan 12 15:05:35 2018 -0800
@@ -64,7 +64,7 @@
     static {
         String keyLengthStr = GetPropertyAction.privilegedGetProperty
             (KEY_LENGTH_PROP);
-        int dsaKeySize = 1024;
+        int dsaKeySize = 2048;
         int rsaKeySize = 2048;
         int dhKeySize = 2048;
         int ecKeySize = 256;
--- a/src/java.base/share/conf/security/java.security	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.base/share/conf/security/java.security	Fri Jan 12 15:05:35 2018 -0800
@@ -676,7 +676,7 @@
 # Example:
 #   jdk.tls.disabledAlgorithms=MD5, SSLv3, DSA, RSA keySize < 2048
 jdk.tls.disabledAlgorithms=SSLv3, RC4, MD5withRSA, DH keySize < 1024, \
-    EC keySize < 224
+    EC keySize < 224, DES40_CBC, RC4_40
 
 #
 # Legacy algorithms for Secure Socket Layer/Transport Layer Security (SSL/TLS)
@@ -737,8 +737,6 @@
 #
 jdk.tls.legacyAlgorithms= \
         K_NULL, C_NULL, M_NULL, \
-        DHE_DSS_EXPORT, DHE_RSA_EXPORT, DH_anon_EXPORT, DH_DSS_EXPORT, \
-        DH_RSA_EXPORT, RSA_EXPORT, \
         DH_anon, ECDH_anon, \
         RC4_128, RC4_40, DES_CBC, DES40_CBC, \
         3DES_EDE_CBC
@@ -985,3 +983,24 @@
 #    java.rmi.dgc.VMID;\
 #    java.rmi.dgc.Lease;\
 #    maxdepth=5;maxarray=10000
+
+# CORBA ORBIorTypeCheckRegistryFilter
+# Type check enhancement for ORB::string_to_object processing
+#
+# An IOR type check filter, if configured, is used by an ORB during
+# an ORB::string_to_object invocation to check the veracity of the type encoded
+# in the ior string. 
+#
+# The filter pattern consists of a semi-colon separated list of class names.
+# The configured list contains the binary class names of the IDL interface types 
+# corresponding to the IDL stub class to be instantiated.
+# As such, a filter specifies a list of IDL stub classes that will be
+# allowed by an ORB when an ORB::string_to_object is invoked.
+# It is used to specify a white list configuration of acceptable
+# IDL stub types which may be contained in a stringified IOR
+# parameter passed as input to an ORB::string_to_object method.
+#
+# Note: This property is currently used by the JDK Reference implementation.
+# It is not guaranteed to be examined and used by other implementations.
+#
+#com.sun.CORBA.ORBIorTypeCheckRegistryFilter=binary_class_name;binary_class_name
--- a/src/java.base/share/lib/security/default.policy	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.base/share/lib/security/default.policy	Fri Jan 12 15:05:35 2018 -0800
@@ -124,6 +124,7 @@
     permission java.util.PropertyPermission "sun.security.pkcs11.allowSingleThreadedModules", "read";
     permission java.util.PropertyPermission "os.name", "read";
     permission java.util.PropertyPermission "os.arch", "read";
+    permission java.util.PropertyPermission "jdk.crypto.KeyAgreement.legacyKDF", "read";
     permission java.security.SecurityPermission "putProviderProperty.*";
     permission java.security.SecurityPermission "clearProviderProperties.*";
     permission java.security.SecurityPermission "removeProviderProperty.*";
--- a/src/java.base/share/native/libjimage/imageFile.cpp	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.base/share/native/libjimage/imageFile.cpp	Fri Jan 12 15:05:35 2018 -0800
@@ -205,12 +205,19 @@
 // Manage a table of open image files.  This table allows multiple access points
 // to share an open image.
 ImageFileReaderTable::ImageFileReaderTable() : _count(0), _max(_growth) {
-    _table = new ImageFileReader*[_max];
+    _table = static_cast<ImageFileReader**>(calloc(_max, sizeof(ImageFileReader*)));
     assert(_table != NULL && "allocation failed");
 }
 
 ImageFileReaderTable::~ImageFileReaderTable() {
-    delete[] _table;
+    for (u4 i = 0; i < _count; i++) {
+        ImageFileReader* image = _table[i];
+
+        if (image != NULL) {
+            delete image;
+        }
+    }
+    free(_table);
 }
 
 // Add a new image entry to the table.
--- a/src/java.base/share/native/libjimage/imageFile.hpp	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.base/share/native/libjimage/imageFile.hpp	Fri Jan 12 15:05:35 2018 -0800
@@ -402,6 +402,7 @@
 // 'opened' by reference point and decremented when 'closed'.    Use of zero
 // leads the ImageFileReader to be actually closed and discarded.
 class ImageFileReader {
+friend class ImageFileReaderTable;
 private:
     // Manage a number of image files such that an image can be shared across
     // multiple uses (ex. loader.)
--- a/src/java.corba/share/classes/com/sun/corba/se/impl/encoding/BufferManagerWriteGrow.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.corba/share/classes/com/sun/corba/se/impl/encoding/BufferManagerWriteGrow.java	Fri Jan 12 15:05:35 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2003, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -26,11 +26,13 @@
 package com.sun.corba.se.impl.encoding;
 
 import com.sun.corba.se.impl.orbutil.ORBConstants;
+import com.sun.corba.se.impl.orbutil.ORBUtility;
 import com.sun.corba.se.impl.encoding.ByteBufferWithInfo;
 import com.sun.corba.se.impl.encoding.BufferManagerWrite;
 import com.sun.corba.se.pept.encoding.OutputObject;
 import com.sun.corba.se.pept.transport.Connection;
 import com.sun.corba.se.spi.orb.ORB;
+import com.sun.corba.se.spi.orb.ORBData;
 
 public class BufferManagerWriteGrow extends BufferManagerWrite
 {
@@ -48,7 +50,20 @@
      * buffer manager as set in the ORB.
      */
     public int getBufferSize() {
-        return orb.getORBData().getGIOPBufferSize();
+        ORBData orbData = null;
+        int bufferSize = ORBConstants.GIOP_DEFAULT_BUFFER_SIZE;
+        if (orb != null) {
+            orbData = orb.getORBData();
+            if (orbData != null) {
+                bufferSize = orbData.getGIOPBufferSize();
+                dprint("BufferManagerWriteGrow.getBufferSize: bufferSize == " + bufferSize);
+            } else {
+                dprint("BufferManagerWriteGrow.getBufferSize: orbData reference is NULL");
+            }
+        } else {
+            dprint("BufferManagerWriteGrow.getBufferSize: orb reference is NULL");
+        }
+        return bufferSize;
     }
 
     public void overflow (ByteBufferWithInfo bbwi)
@@ -89,4 +104,9 @@
      */
     public void close() {}
 
+    private void dprint(String msg) {
+        if (orb.transportDebugFlag) {
+            ORBUtility.dprint(this, msg);
 }
+    }
+}
--- a/src/java.corba/share/classes/com/sun/corba/se/impl/encoding/CDRInputStream_1_0.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.corba/share/classes/com/sun/corba/se/impl/encoding/CDRInputStream_1_0.java	Fri Jan 12 15:05:35 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -725,12 +725,14 @@
     //    IDLEntity.class.isAssignableFrom( clz ).
     // 3. If clz is an interface, use it to create the appropriate
     //    stub factory.
+
     public org.omg.CORBA.Object read_Object(Class clz)
     {
         // In any case, we must first read the IOR.
         IOR ior = IORFactories.makeIOR(parent) ;
-        if (ior.isNil())
+        if (ior.isNil()) {
             return null ;
+        }
 
         PresentationManager.StubFactoryFactory sff = ORB.getStubFactoryFactory() ;
         String codeBase = ior.getProfile().getCodebase() ;
@@ -739,6 +741,7 @@
         if (clz == null) {
             RepositoryId rid = RepositoryId.cache.getId( ior.getTypeId() ) ;
             String className = rid.getClassName() ;
+            orb.validateIORClass(className);
             boolean isIDLInterface = rid.isIDLType() ;
 
             if (className == null || className.equals( "" ))
@@ -761,11 +764,9 @@
         } else {
             // clz is an interface class
             boolean isIDL = IDLEntity.class.isAssignableFrom( clz ) ;
-
             stubFactory = sff.createStubFactory( clz.getName(),
                 isIDL, codeBase, clz, clz.getClassLoader() ) ;
         }
-
         return internalIORToObject( ior, stubFactory, orb ) ;
     }
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/java.corba/share/classes/com/sun/corba/se/impl/ior/IORTypeCheckRegistryImpl.java	Fri Jan 12 15:05:35 2018 -0800
@@ -0,0 +1,179 @@
+/*
+ * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package com.sun.corba.se.impl.ior;
+
+import java.util.Set;
+
+import com.sun.corba.se.impl.orbutil.ORBUtility;
+import com.sun.corba.se.spi.ior.IORTypeCheckRegistry;
+import com.sun.corba.se.spi.orb.ORB;
+
+public class IORTypeCheckRegistryImpl implements IORTypeCheckRegistry {
+
+    private final Set<String> iorTypeNames;
+    private static final Set<String> builtinIorTypeNames;
+    private ORB theOrb;
+
+    static {
+        builtinIorTypeNames = initBuiltinIorTypeNames();
+    }
+
+    public IORTypeCheckRegistryImpl( String filterProperties, ORB orb) {
+        theOrb = orb;
+        iorTypeNames = parseIorClassNameList(filterProperties);
+    }
+
+    /*
+     *
+     * A note on the validation flow:
+     * 1. against the filter class name list
+     * 2. against the builtin class name list
+     */
+
+    @Override
+    public boolean isValidIORType(String iorClassName) {
+        dprintTransport(".isValidIORType : iorClassName == " + iorClassName);
+        return validateIorTypeByName(iorClassName);
+    }
+
+
+    private boolean validateIorTypeByName(String iorClassName) {
+        dprintTransport(".validateIorTypeByName : iorClassName == " + iorClassName);
+        boolean isValidType;
+
+        isValidType = checkIorTypeNames(iorClassName);
+
+        if (!isValidType) {
+            isValidType = checkBuiltinClassNames(iorClassName);
+        }
+
+        dprintTransport(".validateIorTypeByName : isValidType == " + isValidType);
+        return isValidType;
+    }
+
+
+    /*
+     * check if the class name corresponding to an IOR Type name
+     * is in the ior class name list as generated from the filter property.
+     * So if the IOR type is recorded in the registry then allow the creation of the
+     * stub factory and let it resolve and load the class. That is if current
+     * type check deliberation permits.
+     * IOR Type names are configured by the filter property
+     */
+
+    private boolean checkIorTypeNames(
+            String theIorClassName) {
+        return (iorTypeNames != null) && (iorTypeNames.contains(theIorClassName));
+    }
+
+    /*
+     * Check the IOR interface class name against the set of
+     * class names that correspond to the builtin JDK IDL stub classes.
+     */
+
+    private boolean  checkBuiltinClassNames(
+            String theIorClassName) {
+        return builtinIorTypeNames.contains(theIorClassName);
+    }
+
+
+    private Set<String> parseIorClassNameList(String filterProperty) {
+        Set<String> _iorTypeNames = null;
+        if (filterProperty != null) {
+            String[] tempIorClassNames = filterProperty.split(";");
+            _iorTypeNames = Set.<String>of(tempIorClassNames);
+            if (theOrb.orbInitDebugFlag) {
+                dprintConfiguredIorTypeNames();
+            }
+        }
+        return _iorTypeNames;
+    }
+
+
+    private static Set<String> initBuiltinIorTypeNames() {
+        Set<Class<?>> builtInCorbaStubTypes = initBuiltInCorbaStubTypes();
+        String [] tempBuiltinIorTypeNames = new String[builtInCorbaStubTypes.size()];
+        int i = 0;
+        for (Class<?> _stubClass: builtInCorbaStubTypes) {
+            tempBuiltinIorTypeNames[i++] = _stubClass.getName();
+        }
+        return  Set.<String>of(tempBuiltinIorTypeNames);
+    }
+
+    private static Set<Class<?>> initBuiltInCorbaStubTypes() {
+        Class<?> tempBuiltinCorbaStubTypes[] = {
+                com.sun.corba.se.spi.activation.Activator.class,
+                com.sun.corba.se.spi.activation._ActivatorStub.class,
+                com.sun.corba.se.spi.activation._InitialNameServiceStub.class,
+                com.sun.corba.se.spi.activation._LocatorStub.class,
+                com.sun.corba.se.spi.activation._RepositoryStub.class,
+                com.sun.corba.se.spi.activation._ServerManagerStub.class,
+                com.sun.corba.se.spi.activation._ServerStub.class,
+                org.omg.CosNaming.BindingIterator.class,
+                org.omg.CosNaming._BindingIteratorStub.class,
+                org.omg.CosNaming.NamingContextExt.class,
+                org.omg.CosNaming._NamingContextExtStub.class,
+                org.omg.CosNaming.NamingContext.class,
+                org.omg.CosNaming._NamingContextStub.class,
+                org.omg.DynamicAny.DynAnyFactory.class,
+                org.omg.DynamicAny._DynAnyFactoryStub.class,
+                org.omg.DynamicAny.DynAny.class,
+                org.omg.DynamicAny._DynAnyStub.class,
+                org.omg.DynamicAny.DynArray.class,
+                org.omg.DynamicAny._DynArrayStub.class,
+                org.omg.DynamicAny.DynEnum.class,
+                org.omg.DynamicAny._DynEnumStub.class,
+                org.omg.DynamicAny.DynFixed.class,
+                org.omg.DynamicAny._DynFixedStub.class,
+                org.omg.DynamicAny.DynSequence.class,
+                org.omg.DynamicAny._DynSequenceStub.class,
+                org.omg.DynamicAny.DynStruct.class,
+                org.omg.DynamicAny._DynStructStub.class,
+                org.omg.DynamicAny.DynUnion.class,
+                org.omg.DynamicAny._DynUnionStub.class,
+                org.omg.DynamicAny._DynValueStub.class,
+                org.omg.DynamicAny.DynValue.class,
+                org.omg.PortableServer.ServantActivator.class,
+                org.omg.PortableServer._ServantActivatorStub.class,
+                org.omg.PortableServer.ServantLocator.class,
+                org.omg.PortableServer._ServantLocatorStub.class };
+        return Set.<Class<?>>of(tempBuiltinCorbaStubTypes);
+    }
+
+    private void dprintConfiguredIorTypeNames() {
+        if (iorTypeNames != null) {
+            for (String iorTypeName : iorTypeNames) {
+                ORBUtility.dprint(this, ".dprintConfiguredIorTypeNames: " + iorTypeName);
+            }
+        }
+    }
+
+    private void dprintTransport(String msg) {
+        if (theOrb.transportDebugFlag) {
+            ORBUtility.dprint(this, msg);
+        }
+    }
+}
--- a/src/java.corba/share/classes/com/sun/corba/se/impl/orb/ORBImpl.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.corba/share/classes/com/sun/corba/se/impl/orb/ORBImpl.java	Fri Jan 12 15:05:35 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -54,6 +54,7 @@
 
 import java.security.PrivilegedAction;
 import java.security.AccessController;
+import java.security.Security;
 
 import javax.rmi.CORBA.Util;
 import javax.rmi.CORBA.ValueHandler;
@@ -90,6 +91,7 @@
 import com.sun.corba.se.pept.transport.TransportManager;
 
 import com.sun.corba.se.spi.ior.IOR;
+import com.sun.corba.se.spi.ior.IORTypeCheckRegistry;
 import com.sun.corba.se.spi.ior.IdentifiableFactoryFinder;
 import com.sun.corba.se.spi.ior.TaggedComponentFactoryFinder;
 import com.sun.corba.se.spi.ior.IORFactories;
@@ -124,6 +126,7 @@
 import com.sun.corba.se.spi.transport.CorbaContactInfoListFactory;
 import com.sun.corba.se.spi.transport.CorbaTransportManager;
 import com.sun.corba.se.spi.legacy.connection.LegacyServerSocketManager;
+import com.sun.corba.se.spi.logging.CORBALogDomains;
 import com.sun.corba.se.spi.copyobject.CopierManager;
 import com.sun.corba.se.spi.presentation.rmi.PresentationDefaults;
 import com.sun.corba.se.spi.presentation.rmi.PresentationManager;
@@ -145,6 +148,7 @@
 import com.sun.corba.se.impl.encoding.CachedCodeBase;
 import com.sun.corba.se.impl.interceptors.PIHandlerImpl;
 import com.sun.corba.se.impl.interceptors.PINoOpHandlerImpl;
+import com.sun.corba.se.impl.ior.IORTypeCheckRegistryImpl;
 import com.sun.corba.se.impl.ior.TaggedComponentFactoryFinderImpl;
 import com.sun.corba.se.impl.ior.TaggedProfileFactoryFinderImpl;
 import com.sun.corba.se.impl.ior.TaggedProfileTemplateFactoryFinderImpl;
@@ -226,6 +230,8 @@
 
     private ServiceContextRegistry serviceContextRegistry ;
 
+    private IORTypeCheckRegistry iorTypeCheckRegistry;
+
     // Needed here to implement connect/disconnect
     private TOAFactory toaFactory ;
 
@@ -274,6 +280,8 @@
     // insNamingDelegate.
     private final Object resolverLock = new Object() ;
 
+    private static final String IORTYPECHECKREGISTRY_FILTER_PROPNAME = "com.sun.CORBA.ORBIorTypeCheckRegistryFilter";
+
     private TaggedComponentFactoryFinder taggedComponentFactoryFinder ;
 
     private IdentifiableFactoryFinder taggedProfileFactoryFinder ;
@@ -411,6 +419,39 @@
             };
 
         serviceContextRegistry = new ServiceContextRegistry( this ) ;
+
+    }
+
+
+    private void initIORTypeCheckRegistry() {
+        String filterProps = AccessController
+                .doPrivileged(new PrivilegedAction<String>() {
+                    public String run() {
+                        String props = System
+                                .getProperty(IORTYPECHECKREGISTRY_FILTER_PROPNAME);
+                        if (props == null) {
+                            props = Security
+                                    .getProperty(IORTYPECHECKREGISTRY_FILTER_PROPNAME);
+                        }
+                        return props;
+                    }
+                });
+        if (filterProps != null) {
+            try {
+                iorTypeCheckRegistry = new IORTypeCheckRegistryImpl(filterProps, this);
+            } catch (Exception ex) {
+                throw wrapper.bootstrapException(ex);
+            }
+
+            if (this.orbInitDebugFlag) {
+                dprint(".initIORTypeCheckRegistry, IORTypeCheckRegistryImpl created for properties == "
+                        + filterProps);
+            }
+        } else {
+            if (this.orbInitDebugFlag) {
+                dprint(".initIORTypeCheckRegistry, IORTypeCheckRegistryImpl NOT created for properties == ");
+            }
+        }
     }
 
     protected void setDebugFlags( String[] args )
@@ -494,6 +535,8 @@
         getThreadPoolManager();
 
         super.getByteBufferPool();
+
+        initIORTypeCheckRegistry();
     }
 
     private synchronized POAFactory getPOAFactory()
@@ -2089,6 +2132,17 @@
         }
         return copierManager ;
     }
+
+    @Override
+    public void validateIORClass(String iorClassName) {
+        if (iorTypeCheckRegistry != null) {
+            if (!iorTypeCheckRegistry.isValidIORType(iorClassName)) {
+                throw ORBUtilSystemException.get( this,
+                        CORBALogDomains.OA_IOR ).badStringifiedIor();
+            }
+        }
+    }
+
 } // Class ORBImpl
 
 ////////////////////////////////////////////////////////////////////////
--- a/src/java.corba/share/classes/com/sun/corba/se/impl/orb/ORBSingleton.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.corba/share/classes/com/sun/corba/se/impl/orb/ORBSingleton.java	Fri Jan 12 15:05:35 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -768,6 +768,13 @@
     public CopierManager getCopierManager() {
         return null ;
     }
+
+    @Override
+    public void validateIORClass(String iorClassName) {
+        getFullORB().validateIORClass(iorClassName);
+
+    }
+
 }
 
 // End of file.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/java.corba/share/classes/com/sun/corba/se/spi/ior/IORTypeCheckRegistry.java	Fri Jan 12 15:05:35 2018 -0800
@@ -0,0 +1,31 @@
+/*
+ * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package com.sun.corba.se.spi.ior;
+
+public interface IORTypeCheckRegistry {
+    public boolean isValidIORType(String iorClassName);
+}
+
--- a/src/java.corba/share/classes/com/sun/corba/se/spi/orb/ORB.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.corba/share/classes/com/sun/corba/se/spi/orb/ORB.java	Fri Jan 12 15:05:35 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -121,6 +121,7 @@
     public boolean shutdownDebugFlag = false;
     public boolean giopDebugFlag = false;
     public boolean invocationTimingDebugFlag = false ;
+    public boolean orbInitDebugFlag = false ;
 
     // SystemException log wrappers.  Protected so that they can be used in
     // subclasses.
@@ -487,6 +488,24 @@
     public abstract ThreadPoolManager getThreadPoolManager();
 
     public abstract CopierManager getCopierManager() ;
+
+    /*
+     * This method is called to verify that a stringified IOR passed to
+     * an org.omg.CORBA.ORB::string_to_object method contains a valid and acceptable IOR type.
+     * If an ORB is configured with IOR type checking enabled,
+     * the ORB executes a IOR type registry lookup to
+     * validate that the class name extract from a type id in
+     * a stringified IOR is a known and accepted type.
+     * A CORBA {@code org.omg.CORBA.DATA_CONVERSION} exception will be thrown should the type check fail.
+     *
+     * @param iorClassName
+     *        a string representing the class name corresponding to the type id of an IOR
+     * @throws org.omg.CORBA.DATA_CONVERSION
+     *           exception with an indication that it is a "Bad stringified IOR", which is thrown
+     *           when the type check fails.
+     */
+    public abstract void validateIORClass(String iorClassName);
+
 }
 
 // End of file.
--- a/src/java.desktop/share/classes/java/awt/color/ICC_ColorSpace.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.desktop/share/classes/java/awt/color/ICC_ColorSpace.java	Fri Jan 12 15:05:35 2018 -0800
@@ -128,6 +128,18 @@
     }
 
     /**
+     * Validate an ICC_ColorSpace read from an object input stream
+     */
+    private void readObject(java.io.ObjectInputStream s)
+        throws ClassNotFoundException, java.io.IOException {
+
+        s.defaultReadObject();
+        if (thisProfile == null) {
+            thisProfile = ICC_Profile.getInstance(ColorSpace.CS_sRGB);
+        }
+    }
+
+    /**
     * Returns the ICC_Profile for this ICC_ColorSpace.
     * @return the ICC_Profile for this ICC_ColorSpace.
     */
--- a/src/java.desktop/share/classes/java/awt/geom/Path2D.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.desktop/share/classes/java/awt/geom/Path2D.java	Fri Jan 12 15:05:35 2018 -0800
@@ -25,13 +25,14 @@
 
 package java.awt.geom;
 
+import java.awt.Rectangle;
 import java.awt.Shape;
-import java.awt.Rectangle;
-import sun.awt.geom.Curve;
 import java.io.Serializable;
 import java.io.StreamCorruptedException;
 import java.util.Arrays;
 
+import sun.awt.geom.Curve;
+
 /**
  * The {@code Path2D} class provides a simple, yet flexible
  * shape which represents an arbitrary geometric path.
@@ -2625,9 +2626,12 @@
             throw new java.io.InvalidObjectException(iae.getMessage());
         }
 
-        pointTypes = new byte[(nT < 0) ? INIT_SIZE : nT];
-        if (nC < 0) {
-            nC = INIT_SIZE * 2;
+        // Accept the size from the stream only if it is less than INIT_SIZE
+        // otherwise the size will be based on the real data in the stream
+        pointTypes = new byte[(nT < 0 || nT > INIT_SIZE) ? INIT_SIZE : nT];
+        final int initX2 = INIT_SIZE * 2;
+        if (nC < 0 || nC > initX2) {
+            nC = initX2;
         }
         if (storedbl) {
             ((Path2D.Double) this).doubleCoords = new double[nC];
--- a/src/java.desktop/share/classes/javax/swing/text/DefaultEditorKit.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.desktop/share/classes/javax/swing/text/DefaultEditorKit.java	Fri Jan 12 15:05:35 2018 -0800
@@ -110,7 +110,7 @@
      * @return the command list
      */
     public Action[] getActions() {
-        return defaultActions;
+        return defaultActions.clone();
     }
 
     /**
--- a/src/java.desktop/share/classes/javax/swing/text/html/CSS.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.desktop/share/classes/javax/swing/text/html/CSS.java	Fri Jan 12 15:05:35 2018 -0800
@@ -26,21 +26,27 @@
 
 import java.awt.Color;
 import java.awt.Font;
-import java.awt.GraphicsEnvironment;
-import java.awt.Toolkit;
 import java.awt.HeadlessException;
 import java.awt.Image;
-import java.io.*;
-import java.lang.reflect.Method;
+import java.awt.Toolkit;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.Serializable;
+import java.net.MalformedURLException;
 import java.net.URL;
-import java.net.MalformedURLException;
 import java.util.Enumeration;
 import java.util.Hashtable;
 import java.util.Vector;
-import java.util.Locale;
+
 import javax.swing.ImageIcon;
 import javax.swing.SizeRequirements;
-import javax.swing.text.*;
+import javax.swing.text.AttributeSet;
+import javax.swing.text.Element;
+import javax.swing.text.MutableAttributeSet;
+import javax.swing.text.SimpleAttributeSet;
+import javax.swing.text.StyleConstants;
+import javax.swing.text.StyleContext;
+import javax.swing.text.View;
 
 /**
  * Defines a set of
@@ -3568,7 +3574,7 @@
 
         // Reconstruct the hashtable.
         int numValues = s.readInt();
-        valueConvertor = new Hashtable<>(Math.max(1, numValues));
+        valueConvertor = new Hashtable<>();
         while (numValues-- > 0) {
             Object key = s.readObject();
             Object value = s.readObject();
--- a/src/java.desktop/share/native/liblcms/LCMS.c	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.desktop/share/native/liblcms/LCMS.c	Fri Jan 12 15:05:35 2018 -0800
@@ -644,7 +644,12 @@
 {
     jclass clsLcmsProfile;
     jobject cmmProfile;
-    jfieldID fid = (*env)->GetFieldID (env,
+    jfieldID fid;
+
+    if (pf == NULL) {
+        return NULL;
+    }
+    fid = (*env)->GetFieldID (env,
         (*env)->GetObjectClass(env, pf),
         "cmmProfile", "Lsun/java2d/cmm/Profile;");
     if (fid == NULL) {
--- a/src/java.desktop/unix/native/libawt_xawt/awt/gtk2_interface.c	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.desktop/unix/native/libawt_xawt/awt/gtk2_interface.c	Fri Jan 12 15:05:35 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -761,46 +761,41 @@
     }
 
     /*
-     * Strip the AT-SPI GTK_MODULEs if present
+     * Strip the AT-SPI GTK_MODULES if present
      */
     gtk_modules_env = getenv ("GTK_MODULES");
+    if ((gtk_modules_env && strstr(gtk_modules_env, "atk-bridge")) ||
+        (gtk_modules_env && strstr(gtk_modules_env, "gail"))) {
+        /* careful, strtok modifies its args */
+        gchar *tmp_env = strdup(gtk_modules_env);
+        if (tmp_env) {
+            /* the new env will be smaller than the old one */
+            gchar *s, *new_env = SAFE_SIZE_STRUCT_ALLOC(malloc,
+                    sizeof(ENV_PREFIX), 1, strlen (gtk_modules_env));
 
-    if (gtk_modules_env && strstr (gtk_modules_env, "atk-bridge") ||
-        gtk_modules_env && strstr (gtk_modules_env, "gail"))
-    {
-        /* the new env will be smaller than the old one */
-        gchar *s, *new_env = SAFE_SIZE_STRUCT_ALLOC(malloc,
-                sizeof(ENV_PREFIX), 1, strlen (gtk_modules_env));
-
-        if (new_env != NULL )
-        {
-            /* careful, strtok modifies its args */
-            gchar *tmp_env = strdup (gtk_modules_env);
-            strcpy(new_env, ENV_PREFIX);
+            if (new_env) {
+                strcpy(new_env, ENV_PREFIX);
 
-            /* strip out 'atk-bridge' and 'gail' */
-            size_t PREFIX_LENGTH = strlen(ENV_PREFIX);
-            while (s = strtok(tmp_env, ":"))
-            {
-                if ((!strstr (s, "atk-bridge")) && (!strstr (s, "gail")))
-                {
-                    if (strlen (new_env) > PREFIX_LENGTH) {
-                        new_env = strcat (new_env, ":");
+                /* strip out 'atk-bridge' and 'gail' */
+                size_t PREFIX_LENGTH = strlen(ENV_PREFIX);
+                gchar *tmp_ptr = NULL;
+                for (s = strtok_r(tmp_env, ":", &tmp_ptr); s;
+                     s = strtok_r(NULL, ":", &tmp_ptr)) {
+                    if ((!strstr(s, "atk-bridge")) && (!strstr(s, "gail"))) {
+                        if (strlen(new_env) > PREFIX_LENGTH) {
+                            new_env = strcat(new_env, ":");
+                        }
+                        new_env = strcat(new_env, s);
                     }
-                    new_env = strcat(new_env, s);
                 }
-                if (tmp_env)
-                {
-                    free (tmp_env);
-                    tmp_env = NULL; /* next call to strtok arg1==NULL */
+                if (putenv(new_env) != 0) {
+                    /* no free() on success, putenv() doesn't copy string */
+                    free(new_env);
                 }
             }
-            putenv (new_env);
-            free (new_env);
-            free (tmp_env);
+            free(tmp_env);
         }
     }
-
     /*
      * GTK should be initialized with gtk_init_check() before use.
      *
--- a/src/java.desktop/unix/native/libawt_xawt/awt/gtk3_interface.c	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.desktop/unix/native/libawt_xawt/awt/gtk3_interface.c	Fri Jan 12 15:05:35 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -580,42 +580,39 @@
     }
 
     /*
-     * Strip the AT-SPI GTK_MODULEs if present
+     * Strip the AT-SPI GTK_MODULES if present
      */
     gtk_modules_env = getenv ("GTK_MODULES");
-    if (gtk_modules_env && strstr (gtk_modules_env, "atk-bridge") ||
-        gtk_modules_env && strstr (gtk_modules_env, "gail"))
-    {
-        /* the new env will be smaller than the old one */
-        gchar *s, *new_env = SAFE_SIZE_STRUCT_ALLOC(malloc,
-                sizeof(ENV_PREFIX), 1, strlen (gtk_modules_env));
-
-        if (new_env != NULL )
-        {
-            /* careful, strtok modifies its args */
-            gchar *tmp_env = strdup (gtk_modules_env);
-            strcpy(new_env, ENV_PREFIX);
-
-            /* strip out 'atk-bridge' and 'gail' */
-            size_t PREFIX_LENGTH = strlen(ENV_PREFIX);
-            while (s = strtok(tmp_env, ":"))
-            {
-                if ((!strstr (s, "atk-bridge")) && (!strstr (s, "gail")))
-                {
-                    if (strlen (new_env) > PREFIX_LENGTH) {
-                        new_env = strcat (new_env, ":");
+    if ((gtk_modules_env && strstr(gtk_modules_env, "atk-bridge")) ||
+        (gtk_modules_env && strstr(gtk_modules_env, "gail"))) {
+        /* careful, strtok modifies its args */
+        gchar *tmp_env = strdup(gtk_modules_env);
+        if (tmp_env) {
+            /* the new env will be smaller than the old one */
+            gchar *s, *new_env = SAFE_SIZE_STRUCT_ALLOC(malloc,
+                    sizeof(ENV_PREFIX), 1, strlen (gtk_modules_env));
+
+            if (new_env) {
+                strcpy(new_env, ENV_PREFIX);
+
+                /* strip out 'atk-bridge' and 'gail' */
+                size_t PREFIX_LENGTH = strlen(ENV_PREFIX);
+                gchar *tmp_ptr = NULL;
+                for (s = strtok_r(tmp_env, ":", &tmp_ptr); s;
+                     s = strtok_r(NULL, ":", &tmp_ptr)) {
+                    if ((!strstr(s, "atk-bridge")) && (!strstr(s, "gail"))) {
+                        if (strlen(new_env) > PREFIX_LENGTH) {
+                            new_env = strcat(new_env, ":");
+                        }
+                        new_env = strcat(new_env, s);
                     }
-                    new_env = strcat(new_env, s);
                 }
-                if (tmp_env)
-                {
-                    free (tmp_env);
-                    tmp_env = NULL; /* next call to strtok arg1==NULL */
+                if (putenv(new_env) != 0) {
+                    /* no free() on success, putenv() doesn't copy string */
+                    free(new_env);
                 }
             }
-            putenv (new_env);
-            free (new_env);
-            free (tmp_env);
+            free(tmp_env);
         }
     }
     /*
--- a/src/java.desktop/windows/native/libawt/java2d/d3d/D3DGraphicsDevice.cpp	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.desktop/windows/native/libawt/java2d/d3d/D3DGraphicsDevice.cpp	Fri Jan 12 15:05:35 2018 -0800
@@ -98,7 +98,7 @@
 
     jstring ret = JNU_NewStringPlatform(env, pAdapterId);
 
-    delete pAdapterId;
+    delete[] pAdapterId;
 
     return ret;
 }
--- a/src/java.desktop/windows/native/libawt/windows/WPrinterJob.cpp	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.desktop/windows/native/libawt/windows/WPrinterJob.cpp	Fri Jan 12 15:05:35 2018 -0800
@@ -508,14 +508,14 @@
           names = env->NewObjectArray(cReturned, cls, NULL);
       }
       if (names == NULL || cls == NULL) {
-          delete buf;
+          delete[] buf;
           return names;
       }
 
       for (int i = 0; i < cReturned; i++) {
           utf_str = JNU_NewStringPlatform(env, buf+(buf_len*i));
             if (utf_str == NULL) {
-                delete buf;
+                delete[] buf;
                 return names;
             }
             env->SetObjectArrayElement(names, i, utf_str);
--- a/src/java.desktop/windows/native/libawt/windows/awt_Palette.cpp	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.desktop/windows/native/libawt/windows/awt_Palette.cpp	Fri Jan 12 15:05:35 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -148,7 +148,7 @@
         pEntry->peFlags = PC_EXPLICIT;
     }
     hPal = ::CreatePalette(pLogPal);
-    delete pLogPal;
+    delete[] pLogPal;
     if ( hPal == 0 ) {
         return 0;
     }
--- a/src/java.desktop/windows/native/libawt/windows/awt_Robot.cpp	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.desktop/windows/native/libawt/windows/awt_Robot.cpp	Fri Jan 12 15:05:35 2018 -0800
@@ -285,7 +285,7 @@
 
     // copy pixels into Java array
     env->SetIntArrayRegion(pixelArray, 0, numPixels, (jint *)pixelData);
-    delete pinfo;
+    delete[] pinfo;
 
     // free all the GDI objects we made
     ::SelectObject(hdcMem, hOldBitmap);
--- a/src/java.naming/share/classes/javax/naming/directory/BasicAttributes.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.naming/share/classes/javax/naming/directory/BasicAttributes.java	Fri Jan 12 15:05:35 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -302,8 +302,8 @@
         s.defaultReadObject();  // read in the ignoreCase flag
         int n = s.readInt();    // number of attributes
         attrs = (n >= 1)
-            ? new Hashtable<String,Attribute>(n * 2)
-            : new Hashtable<String,Attribute>(2); // can't have initial size of 0 (grrr...)
+                ? new Hashtable<>(1 + (int) (Math.min(768, n) / .75f))
+                : new Hashtable<>(2); // can't have initial size of 0 (grrr...)
         while (--n >= 0) {
             put((Attribute)s.readObject());
         }
--- a/src/java.naming/share/classes/sun/security/provider/certpath/ldap/LDAPCertStore.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.naming/share/classes/sun/security/provider/certpath/ldap/LDAPCertStore.java	Fri Jan 12 15:05:35 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -136,6 +136,11 @@
                         + params.getClass().getName() + " passed");
         }
 
+        SecurityManager security = System.getSecurityManager();
+        if (security != null) {
+            security.checkConnect(serverName, port);
+        }
+
         Key k = new Key(serverName, port);
         LDAPCertStoreImpl lci = certStoreCache.get(k);
         if (lci == null) {
--- a/src/java.naming/share/classes/sun/security/provider/certpath/ldap/LDAPCertStoreImpl.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.naming/share/classes/sun/security/provider/certpath/ldap/LDAPCertStoreImpl.java	Fri Jan 12 15:05:35 2018 -0800
@@ -26,9 +26,11 @@
 package sun.security.provider.certpath.ldap;
 
 import java.io.ByteArrayInputStream;
-import java.io.IOException;
+import java.net.URI;
 import java.util.*;
+import javax.naming.CompositeName;
 import javax.naming.Context;
+import javax.naming.InvalidNameException;
 import javax.naming.NamingEnumeration;
 import javax.naming.NamingException;
 import javax.naming.NameNotFoundException;
@@ -44,6 +46,7 @@
 import javax.naming.ldap.LdapContext;
 import javax.security.auth.x500.X500Principal;
 
+import com.sun.jndi.ldap.LdapReferralException;
 import sun.security.util.HexDumpEncoder;
 import sun.security.provider.certpath.X509CertificatePair;
 import sun.security.util.Cache;
@@ -181,13 +184,9 @@
         try {
             ctx = new InitialLdapContext(env, null);
             /*
-             * By default, follow referrals unless application has
-             * overridden property in an application resource file.
+             * Always deal with referrals here.
              */
-            Hashtable<?,?> currentEnv = ctx.getEnvironment();
-            if (currentEnv.get(Context.REFERRAL) == null) {
-                ctx.addToEnvironment(Context.REFERRAL, "follow-scheme");
-            }
+            ctx.addToEnvironment(Context.REFERRAL, "throw");
         } catch (NamingException e) {
             if (debug != null) {
                 debug.println("LDAPCertStore.engineInit about to throw "
@@ -223,11 +222,25 @@
         private Map<String, byte[][]> valueMap;
         private final List<String> requestedAttributes;
 
-        LDAPRequest(String name) {
-            this.name = name;
+        LDAPRequest(String name) throws CertStoreException {
+            this.name = checkName(name);
             requestedAttributes = new ArrayList<>(5);
         }
 
+        private String checkName(String name) throws CertStoreException {
+            if (name == null) {
+                throw new CertStoreException("Name absent");
+            }
+            try {
+                if (new CompositeName(name).size() > 1) {
+                    throw new CertStoreException("Invalid name: " + name);
+                }
+            } catch (InvalidNameException ine) {
+                throw new CertStoreException("Invalid name: " + name, ine);
+            }
+            return name;
+        }
+
         String getName() {
             return name;
         }
@@ -242,7 +255,6 @@
         /**
          * Gets one or more binary values from an attribute.
          *
-         * @param name          the location holding the attribute
          * @param attrId                the attribute identifier
          * @return                      an array of binary values (byte arrays)
          * @throws NamingException      if a naming exception occurs
@@ -300,6 +312,39 @@
 
             try {
                 attrs = ctx.getAttributes(name, attrIds);
+            } catch (LdapReferralException lre) {
+                // LdapCtx has a hopCount field to avoid infinite loop
+                while (true) {
+                    try {
+                        String newName = (String) lre.getReferralInfo();
+                        URI newUri = new URI(newName);
+                        if (!newUri.getScheme().equalsIgnoreCase("ldap")) {
+                            throw new IllegalArgumentException("Not LDAP");
+                        }
+                        String newDn = newUri.getPath();
+                        if (newDn != null && newDn.charAt(0) == '/') {
+                            newDn = newDn.substring(1);
+                        }
+                        checkName(newDn);
+                    } catch (Exception e) {
+                        throw new NamingException("Cannot follow referral to "
+                                + lre.getReferralInfo());
+                    }
+                    LdapContext refCtx =
+                            (LdapContext)lre.getReferralContext();
+
+                    // repeat the original operation at the new context
+                    try {
+                        attrs = refCtx.getAttributes(name, attrIds);
+                        break;
+                    } catch (LdapReferralException re) {
+                        lre = re;
+                        continue;
+                    } finally {
+                        // Make sure we close referral context
+                        refCtx.close();
+                    }
+                }
             } catch (CommunicationException ce) {
                 communicationError = true;
                 throw ce;
@@ -513,7 +558,7 @@
      * <code>X509CertSelector</code>), a <code>CertStoreException</code> is
      * thrown.
      *
-     * @param selector a <code>X509CertSelector</code> used to select which
+     * @param xsel a <code>X509CertSelector</code> used to select which
      *  <code>Certificate</code>s should be returned.
      * @return a <code>Collection</code> of <code>X509Certificate</code>s that
      *         match the specified selector
@@ -684,7 +729,7 @@
      * (or the selector is not an <code>X509CRLSelector</code>), a
      * <code>CertStoreException</code> is thrown.
      *
-     * @param selector A <code>X509CRLSelector</code> used to select which
+     * @param xsel A <code>X509CRLSelector</code> used to select which
      *  <code>CRL</code>s should be returned. Specify <code>null</code>
      *  to return all <code>CRL</code>s.
      * @return A <code>Collection</code> of <code>X509CRL</code>s that
--- a/src/java.rmi/share/classes/sun/rmi/registry/RegistryImpl.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.rmi/share/classes/sun/rmi/registry/RegistryImpl.java	Fri Jan 12 15:05:35 2018 -0800
@@ -177,7 +177,7 @@
             }
         } else {
             LiveRef lref = new LiveRef(id, port, csf, ssf);
-            setup(new UnicastServerRef2(lref, RegistryImpl::registryFilter));
+            setup(new UnicastServerRef2(lref, serialFilter));
         }
     }
 
--- a/src/java.security.jgss/share/classes/sun/net/www/protocol/http/spnego/NegotiateCallbackHandler.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.security.jgss/share/classes/sun/net/www/protocol/http/spnego/NegotiateCallbackHandler.java	Fri Jan 12 15:05:35 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -35,6 +35,7 @@
 import javax.security.auth.callback.PasswordCallback;
 import javax.security.auth.callback.UnsupportedCallbackException;
 import sun.net.www.protocol.http.HttpCallerInfo;
+import sun.security.jgss.LoginConfigImpl;
 
 /**
  * @since 1.6
@@ -61,19 +62,28 @@
     private void getAnswer() {
         if (!answered) {
             answered = true;
-            PasswordAuthentication passAuth =
-                    Authenticator.requestPasswordAuthentication(
-                    hci.authenticator,
-                    hci.host, hci.addr, hci.port, hci.protocol,
-                    hci.prompt, hci.scheme, hci.url, hci.authType);
-            /**
-             * To be compatible with existing callback handler implementations,
-             * when the underlying Authenticator is canceled, username and
-             * password are assigned null. No exception is thrown.
-             */
-            if (passAuth != null) {
-                username = passAuth.getUserName();
-                password = passAuth.getPassword();
+            Authenticator auth;
+            if (hci.authenticator != null) {
+                auth = hci.authenticator;
+            } else {
+                auth = LoginConfigImpl.HTTP_USE_GLOBAL_CREDS ?
+                        Authenticator.getDefault() : null;
+            }
+
+            if (auth != null) {
+                PasswordAuthentication passAuth =
+                        auth.requestPasswordAuthenticationInstance(
+                                hci.host, hci.addr, hci.port, hci.protocol,
+                                hci.prompt, hci.scheme, hci.url, hci.authType);
+                /**
+                 * To be compatible with existing callback handler implementations,
+                 * when the underlying Authenticator is canceled, username and
+                 * password are assigned null. No exception is thrown.
+                 */
+                if (passAuth != null) {
+                    username = passAuth.getUserName();
+                    password = passAuth.getPassword();
+                }
             }
         }
     }
--- a/src/java.security.jgss/share/classes/sun/security/jgss/GSSUtil.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.security.jgss/share/classes/sun/security/jgss/GSSUtil.java	Fri Jan 12 15:05:35 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -270,24 +270,17 @@
      */
     public static boolean useSubjectCredsOnly(GSSCaller caller) {
 
-        // HTTP/SPNEGO doesn't use the standard JAAS framework. Instead, it
-        // uses the java.net.Authenticator style, therefore always return
-        // false here.
+        String propValue = GetPropertyAction.privilegedGetProperty(
+                "javax.security.auth.useSubjectCredsOnly");
+
+        // Invalid values should be ignored and the default assumed.
         if (caller instanceof HttpCaller) {
-            return false;
+            // Default for HTTP/SPNEGO is false.
+            return "true".equalsIgnoreCase(propValue);
+        } else {
+            // Default for JGSS is true.
+            return !("false".equalsIgnoreCase(propValue));
         }
-        /*
-         * Don't use GetBooleanAction because the default value in the JRE
-         * (when this is unset) has to treated as true.
-         */
-        String propValue = AccessController.doPrivileged(
-                new GetPropertyAction("javax.security.auth.useSubjectCredsOnly",
-                "true"));
-        /*
-         * This property has to be explicitly set to "false". Invalid
-         * values should be ignored and the default "true" assumed.
-         */
-        return (!propValue.equalsIgnoreCase("false"));
     }
 
     /**
--- a/src/java.security.jgss/share/classes/sun/security/jgss/LoginConfigImpl.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.security.jgss/share/classes/sun/security/jgss/LoginConfigImpl.java	Fri Jan 12 15:05:35 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -29,6 +29,7 @@
 import javax.security.auth.login.AppConfigurationEntry;
 import javax.security.auth.login.Configuration;
 import org.ietf.jgss.Oid;
+import sun.security.action.GetPropertyAction;
 
 /**
  * A Configuration implementation especially designed for JGSS.
@@ -44,6 +45,16 @@
     private static final sun.security.util.Debug debug =
         sun.security.util.Debug.getInstance("gssloginconfig", "\t[GSS LoginConfigImpl]");
 
+    public static final boolean HTTP_USE_GLOBAL_CREDS;
+
+    static {
+        String prop = GetPropertyAction
+                .privilegedGetProperty("http.use.global.creds");
+        //HTTP_USE_GLOBAL_CREDS = "true".equalsIgnoreCase(prop); // default false
+        HTTP_USE_GLOBAL_CREDS = !"false".equalsIgnoreCase(prop); // default true
+    }
+
+
     /**
      * A new instance of LoginConfigImpl must be created for each login request
      * since it's only used by a single (caller, mech) pair
@@ -178,7 +189,11 @@
                 options.put("principal", "*");
                 options.put("isInitiator", "false");
             } else {
-                options.put("useTicketCache", "true");
+                if (caller instanceof HttpCaller && !HTTP_USE_GLOBAL_CREDS) {
+                    options.put("useTicketCache", "false");
+                } else {
+                    options.put("useTicketCache", "true");
+                }
                 options.put("doNotPrompt", "false");
             }
             return new AppConfigurationEntry[] {
--- a/src/java.security.jgss/share/native/libj2gss/GSSLibStub.c	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.security.jgss/share/native/libj2gss/GSSLibStub.c	Fri Jan 12 15:05:35 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -830,7 +830,7 @@
 {
   OM_uint32 minor, major;
   gss_cred_id_t credHdl ;
-  gss_ctx_id_t contextHdl;
+  gss_ctx_id_t contextHdl, contextHdlSave;
   gss_name_t targetName;
   gss_OID mech;
   OM_uint32 flags, aFlags;
@@ -847,7 +847,7 @@
   TRACE0("[GSSLibStub_initContext]");
 
   credHdl = (gss_cred_id_t) jlong_to_ptr(pCred);
-  contextHdl = (gss_ctx_id_t) jlong_to_ptr(
+  contextHdl = contextHdlSave = (gss_ctx_id_t) jlong_to_ptr(
     (*env)->GetLongField(env, jcontextSpi, FID_NativeGSSContext_pContext));
   targetName = (gss_name_t) jlong_to_ptr(pName);
   mech = (gss_OID) jlong_to_ptr((*env)->GetLongField(env, jobj, FID_GSSLibStub_pMech));
@@ -882,10 +882,17 @@
   TRACE2("[GSSLibStub_initContext] after: pContext=%ld, outToken len=%ld",
             (long)contextHdl, (long)outToken.length);
 
+  // update context handle with the latest value if changed
+  // this is to work with both MIT and Solaris. Former deletes half-built
+  // context if error occurs
+  if (contextHdl != contextHdlSave) {
+    (*env)->SetLongField(env, jcontextSpi, FID_NativeGSSContext_pContext,
+                         ptr_to_jlong(contextHdl));
+    TRACE1("[GSSLibStub_initContext] set pContext=%ld", (long)contextHdl);
+  }
+
   if (GSS_ERROR(major) == GSS_S_COMPLETE) {
     /* update member values if needed */
-    (*env)->SetLongField(env, jcontextSpi, FID_NativeGSSContext_pContext,
-                        ptr_to_jlong(contextHdl));
     (*env)->SetIntField(env, jcontextSpi, FID_NativeGSSContext_flags, aFlags);
     TRACE1("[GSSLibStub_initContext] set flags=0x%x", aFlags);
 
@@ -939,7 +946,7 @@
 {
   OM_uint32 minor, major;
   OM_uint32 minor2, major2;
-  gss_ctx_id_t contextHdl;
+  gss_ctx_id_t contextHdl, contextHdlSave;
   gss_cred_id_t credHdl;
   gss_buffer_desc inToken;
   gss_channel_bindings_t cb;
@@ -959,7 +966,7 @@
 
   TRACE0("[GSSLibStub_acceptContext]");
 
-  contextHdl = (gss_ctx_id_t)jlong_to_ptr(
+  contextHdl = contextHdlSave = (gss_ctx_id_t)jlong_to_ptr(
     (*env)->GetLongField(env, jcontextSpi, FID_NativeGSSContext_pContext));
   credHdl = (gss_cred_id_t) jlong_to_ptr(pCred);
   initGSSBuffer(env, jinToken, &inToken);
@@ -996,19 +1003,22 @@
   TRACE3("[GSSLibStub_acceptContext] after: pCred=%ld, pContext=%ld, pDelegCred=%ld",
         (long)credHdl, (long)contextHdl, (long) delCred);
 
+  // update context handle with the latest value if changed
+  // this is to work with both MIT and Solaris. Former deletes half-built
+  // context if error occurs
+  if (contextHdl != contextHdlSave) {
+    (*env)->SetLongField(env, jcontextSpi, FID_NativeGSSContext_pContext,
+                         ptr_to_jlong(contextHdl));
+    TRACE1("[GSSLibStub_acceptContext] set pContext=%ld", (long)contextHdl);
+  }
+
   if (GSS_ERROR(major) == GSS_S_COMPLETE) {
     /* update member values if needed */
-    (*env)->SetLongField(env, jcontextSpi, FID_NativeGSSContext_pContext,
-                        ptr_to_jlong(contextHdl));
-    TRACE1("[GSSLibStub_acceptContext] set pContext=%ld",
-            (long)contextHdl);
-
     // WORKAROUND for a Heimdal bug
     if (delCred == GSS_C_NO_CREDENTIAL) {
         aFlags &= 0xfffffffe;
     }
     (*env)->SetIntField(env, jcontextSpi, FID_NativeGSSContext_flags, aFlags);
-
     TRACE1("[GSSLibStub_acceptContext] set flags=0x%x", aFlags);
 
     if (setTarget) {
--- a/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/lib/ExsltDynamic.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/lib/ExsltDynamic.java	Fri Jan 12 15:05:35 2018 -0800
@@ -1,6 +1,5 @@
 /*
- * reserved comment block
- * DO NOT REMOVE OR ALTER!
+ * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * Licensed to the Apache Software Foundation (ASF) under one or more
@@ -36,6 +35,7 @@
 import com.sun.org.apache.xpath.internal.objects.XNodeSet;
 import com.sun.org.apache.xpath.internal.objects.XNumber;
 import com.sun.org.apache.xpath.internal.objects.XObject;
+import jdk.xml.internal.JdkXmlUtils;
 
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
@@ -410,10 +410,7 @@
         {
           if (lDoc == null)
           {
-            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
-            dbf.setNamespaceAware(true);
-            DocumentBuilder db = dbf.newDocumentBuilder();
-            lDoc = db.newDocument();
+            lDoc = JdkXmlUtils.getDOMDocument();
           }
 
           Element element = null;
--- a/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/lib/ExsltStrings.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/lib/ExsltStrings.java	Fri Jan 12 15:05:35 2018 -0800
@@ -1,6 +1,5 @@
 /*
- * reserved comment block
- * DO NOT REMOVE OR ALTER!
+ * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * Licensed to the Apache Software Foundation (ASF) under one or more
@@ -22,12 +21,8 @@
 package com.sun.org.apache.xalan.internal.lib;
 
 import java.util.StringTokenizer;
-
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.parsers.FactoryConfigurationError;
-import javax.xml.parsers.ParserConfigurationException;
-
 import com.sun.org.apache.xpath.internal.NodeSet;
+import jdk.xml.internal.JdkXmlUtils;
 
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
@@ -51,7 +46,6 @@
  */
 public class ExsltStrings extends ExsltBase
 {
-   static final String JDK_DEFAULT_DOM = "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl";
 
   /**
    * The str:align function aligns a string within another string.
@@ -226,7 +220,7 @@
         token = str.substring(fromIndex);
       }
 
-      Document doc = getDocument();
+      Document doc = JdkXmlUtils.getDOMDocument();
       synchronized (doc)
       {
         Element element = doc.createElement("token");
@@ -290,7 +284,7 @@
     {
       StringTokenizer lTokenizer = new StringTokenizer(toTokenize, delims);
 
-      Document doc = getDocument();
+      Document doc = JdkXmlUtils.getDOMDocument();
       synchronized (doc)
       {
         while (lTokenizer.hasMoreTokens())
@@ -306,7 +300,7 @@
     else
     {
 
-      Document doc = getDocument();
+      Document doc = JdkXmlUtils.getDOMDocument();
       synchronized (doc)
       {
         for (int i = 0; i < toTokenize.length(); i++)
@@ -328,23 +322,4 @@
   {
     return tokenize(toTokenize, " \t\n\r");
   }
-
-    /**
-   * @return an instance of DOM Document
-     */
-   private static Document getDocument()
-   {
-        try
-        {
-            if (System.getSecurityManager() == null) {
-                return DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
-            } else {
-                return DocumentBuilderFactory.newInstance(JDK_DEFAULT_DOM, null).newDocumentBuilder().newDocument();
-            }
-        }
-        catch(ParserConfigurationException pce)
-        {
-            throw new com.sun.org.apache.xml.internal.utils.WrappedRuntimeException(pce);
-        }
-    }
 }
--- a/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/lib/Extensions.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/lib/Extensions.java	Fri Jan 12 15:05:35 2018 -0800
@@ -1,6 +1,5 @@
 /*
- * reserved comment block
- * DO NOT REMOVE OR ALTER!
+ * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * Licensed to the Apache Software Foundation (ASF) under one or more
@@ -23,14 +22,12 @@
 
 import java.util.StringTokenizer;
 
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.parsers.ParserConfigurationException;
-
 import com.sun.org.apache.xalan.internal.extensions.ExpressionContext;
 import com.sun.org.apache.xpath.internal.NodeSet;
 import com.sun.org.apache.xpath.internal.objects.XBoolean;
 import com.sun.org.apache.xpath.internal.objects.XNumber;
 import com.sun.org.apache.xpath.internal.objects.XObject;
+import jdk.xml.internal.JdkXmlUtils;
 
 import org.w3c.dom.Document;
 import org.w3c.dom.DocumentFragment;
@@ -51,7 +48,6 @@
  */
 public class Extensions
 {
-    static final String JDK_DEFAULT_DOM = "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl";
   /**
    * Constructor Extensions
    *
@@ -110,7 +106,7 @@
 
       // This no longer will work right since the DTM.
       // Document myDoc = myProcessor.getContextNode().getOwnerDocument();
-      Document myDoc = getDocument();
+      Document myDoc = JdkXmlUtils.getDOMDocument();
 
         Text textNode = myDoc.createTextNode(textNodeValue);
         DocumentFragment docFrag = myDoc.createDocumentFragment();
@@ -236,7 +232,7 @@
   public static NodeList tokenize(String toTokenize, String delims)
   {
 
-    Document doc = getDocument();
+    Document doc = JdkXmlUtils.getDOMDocument();
 
     StringTokenizer lTokenizer = new StringTokenizer(toTokenize, delims);
     NodeSet resultSet = new NodeSet();
@@ -269,23 +265,4 @@
   {
     return tokenize(toTokenize, " \t\n\r");
   }
-
-    /**
-   * @return an instance of DOM Document
-     */
-   private static Document getDocument()
-   {
-        try
-        {
-            if (System.getSecurityManager() == null) {
-                return DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
-            } else {
-                return DocumentBuilderFactory.newInstance(JDK_DEFAULT_DOM, null).newDocumentBuilder().newDocument();
-            }
-        }
-        catch(ParserConfigurationException pce)
-        {
-            throw new com.sun.org.apache.xml.internal.utils.WrappedRuntimeException(pce);
-        }
-    }
 }
--- a/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/utils/FactoryImpl.java	Fri Jan 12 10:05:00 2018 -0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,57 +0,0 @@
-/*
- * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.  Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.sun.org.apache.xalan.internal.utils;
-
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.parsers.SAXParserFactory;
-
-/**
- *
- * @author huizhe wang
- */
-public class FactoryImpl {
-
-    static final String DBF = "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl";
-    static final String SF = "com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl";
-
-    static public DocumentBuilderFactory getDOMFactory(boolean useServicesMechanism) {
-        DocumentBuilderFactory dbf =
-            useServicesMechanism ?
-            DocumentBuilderFactory.newInstance() :
-            DocumentBuilderFactory.newInstance( DBF,
-                FactoryImpl.class.getClassLoader());
-
-        return dbf;
-    }
-    static public SAXParserFactory getSAXFactory(boolean useServicesMechanism) {
-                SAXParserFactory factory =
-                    useServicesMechanism ?
-                    SAXParserFactory.newInstance() :
-                    SAXParserFactory.newInstance(SF,
-                        FactoryImpl.class.getClassLoader());
-                return factory;
-    }
-}
--- a/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/Translet.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/Translet.java	Fri Jan 12 15:05:35 2018 -0800
@@ -1,5 +1,6 @@
 /*
- * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2017, Oracle and/or its affiliates. All rights reserved.
+ * @LastModified: Oct 2017
  */
 /*
  * Licensed to the Apache Software Foundation (ASF) under one or more
@@ -49,7 +50,7 @@
     public String[] getUrisArray();
     public int[]    getTypesArray();
     public String[] getNamespaceArray();
-    public boolean useServicesMechnism();
-    public void setServicesMechnism(boolean flag);
+    public boolean overrideDefaultParser();
+    public void setOverrideDefaultParser(boolean flag);
 
 }
--- a/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/compiler/Parser.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/compiler/Parser.java	Fri Jan 12 15:05:35 2018 -0800
@@ -22,7 +22,6 @@
 
 import com.sun.java_cup.internal.runtime.Symbol;
 import com.sun.org.apache.xalan.internal.XalanConstants;
-import com.sun.org.apache.xalan.internal.utils.FactoryImpl;
 import com.sun.org.apache.xalan.internal.utils.ObjectFactory;
 import com.sun.org.apache.xalan.internal.utils.XMLSecurityManager;
 import com.sun.org.apache.xalan.internal.xsltc.compiler.util.ErrorMsg;
@@ -43,9 +42,6 @@
 import java.util.StringTokenizer;
 import javax.xml.XMLConstants;
 import javax.xml.catalog.CatalogFeatures;
-import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.parsers.SAXParser;
-import javax.xml.parsers.SAXParserFactory;
 import jdk.xml.internal.JdkXmlFeatures;
 import jdk.xml.internal.JdkXmlUtils;
 import jdk.xml.internal.SecuritySupport;
@@ -56,7 +52,6 @@
 import org.xml.sax.SAXException;
 import org.xml.sax.SAXNotRecognizedException;
 import org.xml.sax.SAXNotSupportedException;
-import org.xml.sax.SAXParseException;
 import org.xml.sax.XMLReader;
 import org.xml.sax.helpers.AttributesImpl;
 
@@ -101,11 +96,11 @@
 
     private int _currentImportPrecedence;
 
-    private boolean _useServicesMechanism = true;
+    private boolean _overrideDefaultParser;
 
-    public Parser(XSLTC xsltc, boolean useServicesMechanism) {
+    public Parser(XSLTC xsltc, boolean useOverrideDefaultParser) {
         _xsltc = xsltc;
-        _useServicesMechanism = useServicesMechanism;
+        _overrideDefaultParser = useOverrideDefaultParser;
     }
 
     public void init() {
@@ -465,56 +460,35 @@
      */
     public SyntaxTreeNode parse(InputSource input) {
         try {
-            // Create a SAX parser and get the XMLReader object it uses
-            final SAXParserFactory factory = FactoryImpl.getSAXFactory(_useServicesMechanism);
-
-            if (_xsltc.isSecureProcessing()) {
-                try {
-                    factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
-                }
-                catch (SAXException e) {}
-            }
+            final XMLReader reader = JdkXmlUtils.getXMLReader(_overrideDefaultParser,
+                    _xsltc.isSecureProcessing());
 
-            try {
-                factory.setFeature(Constants.NAMESPACE_FEATURE,true);
-            }
-            catch (ParserConfigurationException | SAXNotRecognizedException | SAXNotSupportedException e) {
-                factory.setNamespaceAware(true);
-            }
+            JdkXmlUtils.setXMLReaderPropertyIfSupport(reader, XMLConstants.ACCESS_EXTERNAL_DTD,
+                    _xsltc.getProperty(XMLConstants.ACCESS_EXTERNAL_DTD), true);
 
-            final SAXParser parser = factory.newSAXParser();
-            try {
-                parser.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD,
-                        _xsltc.getProperty(XMLConstants.ACCESS_EXTERNAL_DTD));
-            } catch (SAXNotRecognizedException e) {
-                ErrorMsg err = new ErrorMsg(ErrorMsg.WARNING_MSG,
-                        parser.getClass().getName() + ": " + e.getMessage());
-                reportError(WARNING, err);
-            }
 
             boolean supportCatalog = true;
             boolean useCatalog = _xsltc.getFeature(JdkXmlFeatures.XmlFeature.USE_CATALOG);
             try {
-                factory.setFeature(JdkXmlUtils.USE_CATALOG,useCatalog);
+                reader.setFeature(JdkXmlUtils.USE_CATALOG, useCatalog);
             }
-            catch (ParserConfigurationException | SAXNotRecognizedException | SAXNotSupportedException e) {
+            catch (SAXNotRecognizedException | SAXNotSupportedException e) {
                 supportCatalog = false;
             }
 
             if (supportCatalog && useCatalog) {
                 try {
                     CatalogFeatures cf = (CatalogFeatures)_xsltc.getProperty(JdkXmlFeatures.CATALOG_FEATURES);
-                    if (cf != null) {
-                        for (CatalogFeatures.Feature f : CatalogFeatures.Feature.values()) {
-                            parser.setProperty(f.getPropertyName(), cf.get(f));
+                        if (cf != null) {
+                            for (CatalogFeatures.Feature f : CatalogFeatures.Feature.values()) {
+                                reader.setProperty(f.getPropertyName(), cf.get(f));
+                            }
                         }
-                    }
                 } catch (SAXNotRecognizedException e) {
                     //shall not happen for internal settings
                 }
             }
 
-            final XMLReader reader = parser.getXMLReader();
             String lastProperty = "";
             try {
                 XMLSecurityManager securityManager =
@@ -525,7 +499,7 @@
                 }
                 if (securityManager.printEntityCountInfo()) {
                     lastProperty = XalanConstants.JDK_ENTITY_COUNT_INFO;
-                    parser.setProperty(XalanConstants.JDK_ENTITY_COUNT_INFO, XalanConstants.JDK_YES);
+                    reader.setProperty(XalanConstants.JDK_ENTITY_COUNT_INFO, XalanConstants.JDK_YES);
                 }
             } catch (SAXException se) {
                 XMLSecurityManager.printWarning(reader.getClass().getName(), lastProperty, se);
@@ -537,13 +511,6 @@
 
             return(parse(reader, input));
         }
-        catch (ParserConfigurationException e) {
-            ErrorMsg err = new ErrorMsg(ErrorMsg.SAX_PARSER_CONFIG_ERR);
-            reportError(ERROR, err);
-        }
-        catch (SAXParseException e){
-            reportError(ERROR, new ErrorMsg(e.getMessage(),e.getLineNumber()));
-        }
         catch (SAXException e) {
             reportError(ERROR, new ErrorMsg(e.getMessage()));
         }
--- a/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/compiler/XSLTC.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/compiler/XSLTC.java	Fri Jan 12 15:05:35 2018 -0800
@@ -135,7 +135,7 @@
      */
     private boolean _isSecureProcessing = false;
 
-    private boolean _useServicesMechanism = true;
+    private boolean _overrideDefaultParser;
 
     /**
      * protocols allowed for external references set by the stylesheet processing instruction, Import and Include element.
@@ -175,8 +175,10 @@
     /**
      * XSLTC compiler constructor
      */
-    public XSLTC(boolean useServicesMechanism, JdkXmlFeatures featureManager) {
-        _parser = new Parser(this, useServicesMechanism);
+    public XSLTC(JdkXmlFeatures featureManager) {
+        _overrideDefaultParser = featureManager.getFeature(
+                JdkXmlFeatures.XmlFeature.JDK_OVERRIDE_PARSER);
+        _parser = new Parser(this, _overrideDefaultParser);
         _xmlFeatures = featureManager;
         _extensionClassLoader = null;
         _externalExtensionFunctions = new HashMap<>();
@@ -195,19 +197,6 @@
     public boolean isSecureProcessing() {
         return _isSecureProcessing;
     }
-    /**
-     * Return the state of the services mechanism feature.
-     */
-    public boolean useServicesMechnism() {
-        return _useServicesMechanism;
-    }
-
-    /**
-     * Set the state of the services mechanism feature.
-     */
-    public void setServicesMechnism(boolean flag) {
-        _useServicesMechanism = flag;
-    }
 
      /**
      * Return the value of the specified feature
--- a/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/runtime/AbstractTranslet.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/runtime/AbstractTranslet.java	Fri Jan 12 15:05:35 2018 -0800
@@ -21,7 +21,6 @@
 package com.sun.org.apache.xalan.internal.xsltc.runtime;
 
 import com.sun.org.apache.xalan.internal.XalanConstants;
-import com.sun.org.apache.xalan.internal.utils.FactoryImpl;
 import com.sun.org.apache.xalan.internal.xsltc.DOM;
 import com.sun.org.apache.xalan.internal.xsltc.DOMCache;
 import com.sun.org.apache.xalan.internal.xsltc.DOMEnhancedForDTM;
@@ -45,6 +44,7 @@
 import javax.xml.parsers.DocumentBuilderFactory;
 import javax.xml.parsers.ParserConfigurationException;
 import javax.xml.transform.Templates;
+import jdk.xml.internal.JdkXmlUtils;
 import org.w3c.dom.DOMImplementation;
 import org.w3c.dom.Document;
 
@@ -106,7 +106,7 @@
     // This is the name of the index used for ID attributes
     private final static String ID_INDEX_NAME = "##id";
 
-    private boolean _useServicesMechanism;
+    private boolean _overrideDefaultParser;
 
     // The OutputStream for redirect function
     private FileOutputStream output = null;
@@ -559,7 +559,7 @@
     {
         try {
             final TransletOutputHandlerFactory factory
-                = TransletOutputHandlerFactory.newInstance();
+                = TransletOutputHandlerFactory.newInstance(_overrideDefaultParser);
 
             String dirStr = new File(filename).getParent();
             if ((null != dirStr) && (dirStr.length() > 0)) {
@@ -761,15 +761,15 @@
     /**
      * Return the state of the services mechanism feature.
      */
-    public boolean useServicesMechnism() {
-        return _useServicesMechanism;
+    public boolean overrideDefaultParser() {
+        return _overrideDefaultParser;
     }
 
     /**
      * Set the state of the services mechanism feature.
      */
-    public void setServicesMechnism(boolean flag) {
-        _useServicesMechanism = flag;
+    public void setOverrideDefaultParser(boolean flag) {
+        _overrideDefaultParser = flag;
     }
 
     /**
@@ -795,7 +795,7 @@
         throws ParserConfigurationException
     {
         if (_domImplementation == null) {
-            DocumentBuilderFactory dbf = FactoryImpl.getDOMFactory(_useServicesMechanism);
+            DocumentBuilderFactory dbf = JdkXmlUtils.getDOMFactory(_overrideDefaultParser);
             _domImplementation = dbf.newDocumentBuilder().getDOMImplementation();
         }
         return _domImplementation.createDocument(uri, qname, null);
--- a/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/runtime/output/TransletOutputHandlerFactory.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/runtime/output/TransletOutputHandlerFactory.java	Fri Jan 12 15:05:35 2018 -0800
@@ -1,5 +1,6 @@
 /*
- * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2017, Oracle and/or its affiliates. All rights reserved.
+ * @LastModified: Oct 2017
  */
 /*
  * Licensed to the Apache Software Foundation (ASF) under one or more
@@ -70,17 +71,17 @@
     private ContentHandler _handler                 = null;
     private LexicalHandler _lexHandler              = null;
 
-    private boolean _useServicesMechanism;
+    private boolean _overrideDefaultParser;
 
     static public TransletOutputHandlerFactory newInstance() {
         return new TransletOutputHandlerFactory(true);
     }
-    static public TransletOutputHandlerFactory newInstance(boolean useServicesMechanism) {
-        return new TransletOutputHandlerFactory(useServicesMechanism);
+    static public TransletOutputHandlerFactory newInstance(boolean overrideDefaultParser) {
+        return new TransletOutputHandlerFactory(overrideDefaultParser);
     }
 
-    public TransletOutputHandlerFactory(boolean useServicesMechanism) {
-        _useServicesMechanism = useServicesMechanism;
+    public TransletOutputHandlerFactory(boolean overrideDefaultParser) {
+        _overrideDefaultParser = overrideDefaultParser;
     }
     public void setOutputType(int outputType) {
         _outputType = outputType;
@@ -195,7 +196,9 @@
                 return result;
 
             case DOM :
-                _handler = (_node != null) ? new SAX2DOM(_node, _nextSibling, _useServicesMechanism) : new SAX2DOM(_useServicesMechanism);
+                _handler = (_node != null) ?
+                        new SAX2DOM(_node, _nextSibling, _overrideDefaultParser) :
+                        new SAX2DOM(_overrideDefaultParser);
                 _lexHandler = (LexicalHandler) _handler;
                 // falls through
             case STAX :
--- a/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/trax/SAX2DOM.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/trax/SAX2DOM.java	Fri Jan 12 15:05:35 2018 -0800
@@ -1,5 +1,6 @@
 /*
- * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2017, Oracle and/or its affiliates. All rights reserved.
+ * @LastModified: Oct 2017
  */
 /*
  * Licensed to the Apache Software Foundation (ASF) under one or more
@@ -25,15 +26,18 @@
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Stack;
-import javax.xml.parsers.DocumentBuilder;
+
 import javax.xml.parsers.DocumentBuilderFactory;
 import javax.xml.parsers.ParserConfigurationException;
+
+import com.sun.org.apache.xalan.internal.xsltc.runtime.Constants;
+import jdk.xml.internal.JdkXmlUtils;
+
 import org.w3c.dom.Comment;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 import org.w3c.dom.Node;
 import org.w3c.dom.ProcessingInstruction;
-import org.w3c.dom.Text;
 import org.xml.sax.Attributes;
 import org.xml.sax.ContentHandler;
 import org.xml.sax.Locator;
@@ -66,16 +70,16 @@
      * synchronization because the Javadoc is not explicit about
      * thread safety.
      */
-    private DocumentBuilderFactory _factory =
-            DocumentBuilderFactory.newInstance();
+    private DocumentBuilderFactory _factory;
     private boolean _internal = true;
 
-    public SAX2DOM(boolean useServicesMechanism) throws ParserConfigurationException {
-        _document = createDocument(useServicesMechanism);
+    public SAX2DOM(boolean overrideDefaultParser) throws ParserConfigurationException {
+        _document = createDocument(overrideDefaultParser);
         _root = _document;
     }
 
-    public SAX2DOM(Node root, Node nextSibling, boolean useServicesMechanism) throws ParserConfigurationException {
+    public SAX2DOM(Node root, Node nextSibling, boolean overrideDefaultParser)
+            throws ParserConfigurationException {
         _root = root;
         if (root instanceof Document) {
           _document = (Document)root;
@@ -84,15 +88,16 @@
           _document = root.getOwnerDocument();
         }
         else {
-          _document = createDocument(useServicesMechanism);
+          _document = createDocument(overrideDefaultParser);
           _root = _document;
         }
 
         _nextSibling = nextSibling;
     }
 
-    public SAX2DOM(Node root, boolean useServicesMechanism) throws ParserConfigurationException {
-        this(root, null, useServicesMechanism);
+    public SAX2DOM(Node root, boolean overrideDefaultParser)
+            throws ParserConfigurationException {
+        this(root, null, overrideDefaultParser);
     }
 
     public Node getDOM() {
@@ -304,18 +309,13 @@
     public void startDTD(String name, String publicId, String systemId)
         throws SAXException {}
 
-    private Document createDocument(boolean useServicesMechanism) throws ParserConfigurationException {
+    private Document createDocument(boolean overrideDefaultParser)
+            throws ParserConfigurationException {
         if (_factory == null) {
-            if (useServicesMechanism) {
-                _factory = DocumentBuilderFactory.newInstance();
-                if (!(_factory instanceof com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl)) {
-                    _internal = false;
-                }
-            } else {
-                _factory = DocumentBuilderFactory.newInstance(
-                  "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl",
-                  SAX2DOM.class.getClassLoader()
-                  );
+            _factory = JdkXmlUtils.getDOMFactory(overrideDefaultParser);
+            _internal = true;
+            if (!(_factory instanceof com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl)) {
+                _internal = false;
             }
         }
         Document doc;
--- a/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/trax/TemplatesHandlerImpl.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/trax/TemplatesHandlerImpl.java	Fri Jan 12 15:05:35 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2017, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * Licensed to the Apache Software Foundation (ASF) under one or more
@@ -98,7 +98,7 @@
         _tfactory = tfactory;
 
         // Instantiate XSLTC and get reference to parser object
-        XSLTC xsltc = new XSLTC(tfactory.useServicesMechnism(), tfactory.getJdkXmlFeatures());
+        XSLTC xsltc = new XSLTC(tfactory.getJdkXmlFeatures());
         if (tfactory.getFeature(XMLConstants.FEATURE_SECURE_PROCESSING))
             xsltc.setSecureProcessing(true);
 
--- a/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/trax/TemplatesImpl.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/trax/TemplatesImpl.java	Fri Jan 12 15:05:35 2018 -0800
@@ -142,9 +142,9 @@
     private transient TransformerFactoryImpl _tfactory = null;
 
     /**
-     * A flag to determine whether the Service Mechanism is used
+     * A flag to determine whether the system-default parser may be overridden
      */
-    private transient boolean _useServicesMechanism;
+    private transient boolean _overrideDefaultParser;
 
     /**
      * protocols allowed for external references set by the stylesheet processing instruction, Import and Include element.
@@ -241,7 +241,7 @@
         _outputProperties = outputProperties;
         _indentNumber = indentNumber;
         _tfactory = tfactory;
-        _useServicesMechanism = tfactory.useServicesMechnism();
+        _overrideDefaultParser = tfactory.overrideDefaultParser();
         _accessExternalStylesheet = (String) tfactory.getAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET);
     }
     /**
@@ -324,8 +324,8 @@
     /**
      * Return the state of the services mechanism feature.
      */
-    public boolean useServicesMechnism() {
-        return _useServicesMechanism;
+    public boolean overrideDefaultParser() {
+        return _overrideDefaultParser;
     }
 
      /**
@@ -556,7 +556,7 @@
                     _class[_transletIndex].getConstructor().newInstance();
             translet.postInitialization();
             translet.setTemplates(this);
-            translet.setServicesMechnism(_useServicesMechanism);
+            translet.setOverrideDefaultParser(_overrideDefaultParser);
             translet.setAllowedProtocols(_accessExternalStylesheet);
             if (_auxClasses != null) {
                 translet.setAuxiliaryClasses(_auxClasses);
--- a/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/trax/TrAXFilter.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/trax/TrAXFilter.java	Fri Jan 12 15:05:35 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2017, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * Licensed to the Apache Software Foundation (ASF) under one or more
@@ -23,11 +23,6 @@
 
 import java.io.IOException;
 
-import javax.xml.XMLConstants;
-import javax.xml.parsers.FactoryConfigurationError;
-import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.parsers.SAXParser;
-import javax.xml.parsers.SAXParserFactory;
 import javax.xml.transform.ErrorListener;
 import javax.xml.transform.Templates;
 import javax.xml.transform.Transformer;
@@ -35,13 +30,13 @@
 import javax.xml.transform.sax.SAXResult;
 
 import com.sun.org.apache.xml.internal.utils.XMLReaderManager;
+import jdk.xml.internal.JdkXmlUtils;
 
 import org.xml.sax.ContentHandler;
 import org.xml.sax.InputSource;
 import org.xml.sax.SAXException;
 import org.xml.sax.XMLReader;
 import org.xml.sax.helpers.XMLFilterImpl;
-import org.xml.sax.helpers.XMLReaderFactory;
 
 /**
  * skeleton extension of XMLFilterImpl for now.
@@ -53,7 +48,7 @@
     private Templates              _templates;
     private TransformerImpl        _transformer;
     private TransformerHandlerImpl _transformerHandler;
-    private boolean _useServicesMechanism = true;
+    private boolean _overrideDefaultParser;
 
     public TrAXFilter(Templates templates)  throws
         TransformerConfigurationException
@@ -61,7 +56,7 @@
         _templates = templates;
         _transformer = (TransformerImpl) templates.newTransformer();
         _transformerHandler = new TransformerHandlerImpl(_transformer);
-        _useServicesMechanism = _transformer.useServicesMechnism();
+        _overrideDefaultParser = _transformer.overrideDefaultParser();
     }
 
     public Transformer getTransformer() {
@@ -69,36 +64,14 @@
     }
 
     private void createParent() throws SAXException {
-        XMLReader parent = null;
-        try {
-            SAXParserFactory pfactory = SAXParserFactory.newInstance();
-            pfactory.setNamespaceAware(true);
-
-            if (_transformer.isSecureProcessing()) {
-                try {
-                    pfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
-                }
-                catch (SAXException e) {}
-            }
-
-            SAXParser saxparser = pfactory.newSAXParser();
-            parent = saxparser.getXMLReader();
-        }
-        catch (ParserConfigurationException e) {
-            throw new SAXException(e);
-        }
-        catch (FactoryConfigurationError e) {
-            throw new SAXException(e.toString());
-        }
-
-        if (parent == null) {
-            parent = XMLReaderFactory.createXMLReader();
-        }
+        XMLReader parent = JdkXmlUtils.getXMLReader(_overrideDefaultParser,
+                _transformer.isSecureProcessing());
 
         // make this XMLReader the parent of this filter
         setParent(parent);
     }
 
+    @Override
     public void parse (InputSource input) throws SAXException, IOException
     {
         XMLReader managedReader = null;
@@ -106,7 +79,7 @@
         try {
             if (getParent() == null) {
                 try {
-                    managedReader = XMLReaderManager.getInstance(_useServicesMechanism)
+                    managedReader = XMLReaderManager.getInstance(_overrideDefaultParser)
                                                     .getXMLReader();
                     setParent(managedReader);
                 } catch (SAXException  e) {
@@ -118,7 +91,7 @@
             getParent().parse(input);
         } finally {
             if (managedReader != null) {
-                XMLReaderManager.getInstance(_useServicesMechanism).releaseXMLReader(managedReader);
+                XMLReaderManager.getInstance(_overrideDefaultParser).releaseXMLReader(managedReader);
             }
         }
     }
--- a/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/trax/TransformerFactoryImpl.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/trax/TransformerFactoryImpl.java	Fri Jan 12 15:05:35 2018 -0800
@@ -21,7 +21,6 @@
 package com.sun.org.apache.xalan.internal.xsltc.trax;
 
 import com.sun.org.apache.xalan.internal.XalanConstants;
-import com.sun.org.apache.xalan.internal.utils.FactoryImpl;
 import com.sun.org.apache.xalan.internal.utils.FeaturePropertyBase;
 import com.sun.org.apache.xalan.internal.utils.ObjectFactory;
 import com.sun.org.apache.xalan.internal.utils.XMLSecurityManager;
@@ -55,15 +54,12 @@
 import javax.xml.catalog.CatalogFeatures;
 import javax.xml.catalog.CatalogManager;
 import javax.xml.catalog.CatalogResolver;
-import javax.xml.parsers.SAXParser;
-import javax.xml.parsers.SAXParserFactory;
 import javax.xml.transform.ErrorListener;
 import javax.xml.transform.Source;
 import javax.xml.transform.Templates;
 import javax.xml.transform.Transformer;
 import javax.xml.transform.TransformerConfigurationException;
 import javax.xml.transform.TransformerException;
-import javax.xml.transform.TransformerFactory;
 import javax.xml.transform.URIResolver;
 import javax.xml.transform.dom.DOMResult;
 import javax.xml.transform.dom.DOMSource;
@@ -79,18 +75,17 @@
 import jdk.xml.internal.JdkXmlUtils;
 import jdk.xml.internal.SecuritySupport;
 import org.xml.sax.InputSource;
+import org.xml.sax.SAXException;
 import org.xml.sax.XMLFilter;
 import org.xml.sax.XMLReader;
-import org.xml.sax.helpers.XMLReaderFactory;
 
 /**
- * Implementation of a JAXP1.1 TransformerFactory for Translets.
+ * Implementation of a JAXP TransformerFactory for Translets.
  * @author G. Todd Miller
  * @author Morten Jorgensen
  * @author Santiago Pericas-Geertsen
  * @LastModified: Nov 2017
  */
-@SuppressWarnings("deprecation") //org.xml.sax.helpers.XMLReaderFactory
 public class TransformerFactoryImpl
     extends SAXTransformerFactory implements SourceLoader, ErrorListener
 {
@@ -216,11 +211,11 @@
     private boolean _isSecureMode = false;
 
     /**
-     * Indicates whether implementation parts should use
-     *   service loader (or similar).
-     * Note the default value (false) is the safe option..
+     * Indicates whether 3rd party parser may be used to override the system-default
+     * Note the default value (false) is the safe option.
+     * Note same as the old property useServicesMechanism
      */
-    private boolean _useServicesMechanism;
+    private boolean _overrideDefaultParser;
 
     /**
      * protocols allowed for external references set by the stylesheet
@@ -259,15 +254,6 @@
      * javax.xml.transform.sax.TransformerFactory implementation.
      */
     public TransformerFactoryImpl() {
-        this(true);
-    }
-
-    public static TransformerFactory newTransformerFactoryNoServiceLoader() {
-        return new TransformerFactoryImpl(false);
-    }
-
-    private TransformerFactoryImpl(boolean useServicesMechanism) {
-        this._useServicesMechanism = useServicesMechanism;
 
         if (System.getSecurityManager() != null) {
             _isSecureMode = true;
@@ -275,6 +261,8 @@
         }
 
         _xmlFeatures = new JdkXmlFeatures(!_isNotSecureProcessing);
+        _overrideDefaultParser = _xmlFeatures.getFeature(
+                JdkXmlFeatures.XmlFeature.JDK_OVERRIDE_PARSER);
         _xmlSecurityPropertyMgr = new XMLSecurityPropertyManager();
         _accessExternalDTD = _xmlSecurityPropertyMgr.getValue(
                 Property.ACCESS_EXTERNAL_DTD);
@@ -594,14 +582,20 @@
                         JdkXmlFeatures.State.FSP, false);
             }
         }
-        else if (name.equals(XalanConstants.ORACLE_FEATURE_SERVICE_MECHANISM)) {
-            //in secure mode, let _useServicesMechanism be determined by the constructor
-            if (!_isSecureMode)
-                _useServicesMechanism = value;
-        }
         else {
+            if (name.equals(XalanConstants.ORACLE_FEATURE_SERVICE_MECHANISM)) {
+                // for compatibility, in secure mode, useServicesMechanism is determined by the constructor
+                if (_isSecureMode) {
+                    return;
+                }
+            }
             if (_xmlFeatures != null &&
                     _xmlFeatures.setFeature(name, JdkXmlFeatures.State.APIPROPERTY, value)) {
+                if (name.equals(JdkXmlUtils.OVERRIDE_PARSER) ||
+                        name.equals(JdkXmlFeatures.ORACLE_FEATURE_SERVICE_MECHANISM)) {
+                    _overrideDefaultParser = _xmlFeatures.getFeature(
+                            JdkXmlFeatures.XmlFeature.JDK_OVERRIDE_PARSER);
+                }
                 return;
             }
 
@@ -666,8 +660,8 @@
     /**
      * Return the state of the services mechanism feature.
      */
-    public boolean useServicesMechnism() {
-        return _useServicesMechanism;
+    public boolean overrideDefaultParser() {
+        return _overrideDefaultParser;
     }
 
      /**
@@ -726,10 +720,9 @@
         throws TransformerConfigurationException {
 
         String baseId;
-        XMLReader reader;
+        XMLReader reader = null;
         InputSource isource;
 
-
         /**
          * Fix for bugzilla bug 24187
          */
@@ -748,24 +741,15 @@
                 dom2sax.setContentHandler( _stylesheetPIHandler);
                 dom2sax.parse();
             } else {
+                if (source instanceof SAXSource) {
+                    reader = ((SAXSource)source).getXMLReader();
+                }
                 isource = SAXSource.sourceToInputSource(source);
                 baseId = isource.getSystemId();
 
-                SAXParserFactory factory = FactoryImpl.getSAXFactory(_useServicesMechanism);
-                factory.setNamespaceAware(true);
-
-                if (!_isNotSecureProcessing) {
-                    try {
-                        factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
-                    }
-                    catch (org.xml.sax.SAXException e) {}
-                }
-
-                SAXParser jaxpParser = factory.newSAXParser();
-
-                reader = jaxpParser.getXMLReader();
                 if (reader == null) {
-                    reader = XMLReaderFactory.createXMLReader();
+                    reader = JdkXmlUtils.getXMLReader(_overrideDefaultParser,
+                            !_isNotSecureProcessing);
                 }
 
                 _stylesheetPIHandler.setBaseId(baseId);
@@ -781,7 +765,7 @@
         } catch (StopParseException e ) {
           // startElement encountered so do not parse further
 
-        } catch (javax.xml.parsers.ParserConfigurationException | org.xml.sax.SAXException | IOException e) {
+        } catch (SAXException | IOException e) {
              throw new TransformerConfigurationException(
              "getAssociatedStylesheets failed", e);
         }
@@ -962,7 +946,7 @@
         }
 
         // Create and initialize a stylesheet compiler
-        final XSLTC xsltc = new XSLTC(_useServicesMechanism, _xmlFeatures);
+        final XSLTC xsltc = new XSLTC(_xmlFeatures);
         if (_debug) xsltc.setDebug(true);
         if (_enableInlining)
                 xsltc.setTemplateInlining(true);
--- a/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/trax/TransformerImpl.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/trax/TransformerImpl.java	Fri Jan 12 15:05:35 2018 -0800
@@ -21,7 +21,6 @@
 package com.sun.org.apache.xalan.internal.xsltc.trax;
 
 import com.sun.org.apache.xalan.internal.XalanConstants;
-import com.sun.org.apache.xalan.internal.utils.FactoryImpl;
 import com.sun.org.apache.xalan.internal.utils.XMLSecurityManager;
 import com.sun.org.apache.xalan.internal.xsltc.DOM;
 import com.sun.org.apache.xalan.internal.xsltc.DOMCache;
@@ -102,8 +101,6 @@
 
     private final static String LEXICAL_HANDLER_PROPERTY =
         "http://xml.org/sax/properties/lexical-handler";
-    private static final String NAMESPACE_FEATURE =
-        "http://xml.org/sax/features/namespaces";
 
     /**
      * Namespace prefixes feature for {@link XMLReader}.
@@ -200,15 +197,10 @@
     private boolean _isSecureProcessing = false;
 
     /**
-     * Indicates whether implementation parts should use
-     *   service loader (or similar).
-     * Note the default value (false) is the safe option..
+     * Indicates whether 3rd party parser may be used to override the system-default
      */
-    private boolean _useServicesMechanism;
-    /**
-     * protocols allowed for external references set by the stylesheet processing instruction, Import and Include element.
-     */
-    private String _accessExternalStylesheet = XalanConstants.EXTERNAL_ACCESS_DEFAULT;
+    private boolean _overrideDefaultParser;
+
      /**
      * protocols allowed for external DTD references in source file and/or stylesheet.
      */
@@ -276,11 +268,10 @@
         _propertiesClone = (Properties) _properties.clone();
         _indentNumber = indentNumber;
         _tfactory = tfactory;
-        _useServicesMechanism = _tfactory.useServicesMechnism();
-        _accessExternalStylesheet = (String)_tfactory.getAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET);
+        _overrideDefaultParser = _tfactory.overrideDefaultParser();
         _accessExternalDTD = (String)_tfactory.getAttribute(XMLConstants.ACCESS_EXTERNAL_DTD);
         _securityManager = (XMLSecurityManager)_tfactory.getAttribute(XalanConstants.SECURITY_MANAGER);
-        _readerManager = XMLReaderManager.getInstance(_useServicesMechanism);
+        _readerManager = XMLReaderManager.getInstance(_overrideDefaultParser);
         _readerManager.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, _accessExternalDTD);
         _readerManager.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, _isSecureProcessing);
         _readerManager.setProperty(XalanConstants.SECURITY_MANAGER, _securityManager);
@@ -317,15 +308,15 @@
     /**
      * Return the state of the services mechanism feature.
      */
-    public boolean useServicesMechnism() {
-        return _useServicesMechanism;
+    public boolean overrideDefaultParser() {
+        return _overrideDefaultParser;
     }
 
     /**
      * Set the state of the services mechanism feature.
      */
-    public void setServicesMechnism(boolean flag) {
-        _useServicesMechanism = flag;
+    public void setOverrideDefaultParser(boolean flag) {
+        _overrideDefaultParser = flag;
     }
 
     /**
@@ -409,7 +400,7 @@
         // Get encoding using getProperty() to use defaults
         _encoding = _properties.getProperty(OutputKeys.ENCODING);
 
-        _tohFactory = TransletOutputHandlerFactory.newInstance(_useServicesMechanism);
+        _tohFactory = TransletOutputHandlerFactory.newInstance(_overrideDefaultParser);
         _tohFactory.setEncoding(_encoding);
         if (_method != null) {
             _tohFactory.setOutputMethod(_method);
@@ -579,7 +570,7 @@
                  if (_dtmManager == null) {
                      _dtmManager =
                          _tfactory.createNewDTMManagerInstance();
-                     _dtmManager.setServicesMechnism(_useServicesMechanism);
+                     _dtmManager.setOverrideDefaultParser(_overrideDefaultParser);
                  }
                  dom = (DOM)_dtmManager.getDTM(source, false, wsfilter, true,
                                               false, false, 0, hasIdCall);
@@ -754,7 +745,7 @@
 
                 boolean supportCatalog = true;
 
-                DocumentBuilderFactory builderF = FactoryImpl.getDOMFactory(_useServicesMechanism);
+                DocumentBuilderFactory builderF = JdkXmlUtils.getDOMFactory(_overrideDefaultParser);
                 try {
                     builderF.setFeature(XMLConstants.USE_CATALOG, _useCatalog);
                 } catch (ParserConfigurationException e) {
--- a/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/trax/Util.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/trax/Util.java	Fri Jan 12 15:05:35 2018 -0800
@@ -21,7 +21,6 @@
 package com.sun.org.apache.xalan.internal.xsltc.trax;
 
 import com.sun.org.apache.xalan.internal.XalanConstants;
-import com.sun.org.apache.xalan.internal.utils.FactoryImpl;
 import com.sun.org.apache.xalan.internal.utils.XMLSecurityManager;
 import com.sun.org.apache.xalan.internal.xsltc.compiler.XSLTC;
 import com.sun.org.apache.xalan.internal.xsltc.compiler.util.ErrorMsg;
@@ -30,8 +29,6 @@
 import javax.xml.XMLConstants;
 import javax.xml.catalog.CatalogFeatures;
 import javax.xml.catalog.CatalogFeatures.Feature;
-import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.parsers.SAXParserFactory;
 import javax.xml.stream.XMLEventReader;
 import javax.xml.stream.XMLStreamReader;
 import javax.xml.transform.Source;
@@ -42,13 +39,13 @@
 import javax.xml.transform.stream.StreamSource;
 import jdk.xml.internal.JdkXmlFeatures;
 import jdk.xml.internal.JdkXmlUtils;
+import jdk.xml.internal.SecuritySupport;
 import org.w3c.dom.Document;
 import org.xml.sax.InputSource;
 import org.xml.sax.SAXException;
 import org.xml.sax.SAXNotRecognizedException;
 import org.xml.sax.SAXNotSupportedException;
 import org.xml.sax.XMLReader;
-import org.xml.sax.helpers.XMLReaderFactory;
 
 /**
  * @author Santiago Pericas-Geertsen
@@ -57,6 +54,7 @@
  */
 @SuppressWarnings("deprecation") //org.xml.sax.helpers.XMLReaderFactory
 public final class Util {
+    private static final String property = "org.xml.sax.driver";
 
     public static String baseName(String name) {
         return com.sun.org.apache.xalan.internal.xsltc.compiler.util.Util.baseName(name);
@@ -89,54 +87,18 @@
                 try {
                     XMLReader reader = sax.getXMLReader();
 
-                     /*
-                      * Fix for bug 24695
-                      * According to JAXP 1.2 specification if a SAXSource
-                      * is created using a SAX InputSource the Transformer or
-                      * TransformerFactory creates a reader via the
-                      * XMLReaderFactory if setXMLReader is not used
-                      */
-
                     if (reader == null) {
-                       try {
-                           reader= XMLReaderFactory.createXMLReader();
-                           try {
-                                reader.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING,
-                                            xsltc.isSecureProcessing());
-                           } catch (SAXNotRecognizedException e) {
-                                XMLSecurityManager.printWarning(reader.getClass().getName(),
-                                        XMLConstants.FEATURE_SECURE_PROCESSING, e);
-                           }
-                       } catch (Exception e ) {
-                           try {
-
-                               //Incase there is an exception thrown
-                               // resort to JAXP
-                               SAXParserFactory parserFactory = FactoryImpl.getSAXFactory(xsltc.useServicesMechnism());
-                               parserFactory.setNamespaceAware(true);
-
-                               if (xsltc.isSecureProcessing()) {
-                                  try {
-                                      parserFactory.setFeature(
-                                          XMLConstants.FEATURE_SECURE_PROCESSING, true);
-                                  }
-                                  catch (org.xml.sax.SAXException se) {}
-                               }
-
-                               reader = parserFactory.newSAXParser()
-                                     .getXMLReader();
-
-
-                           } catch (ParserConfigurationException pce ) {
-                               throw new TransformerConfigurationException
-                                 ("ParserConfigurationException" ,pce);
-                           }
-                       }
+                        boolean overrideDefaultParser = xsltc.getFeature(
+                                JdkXmlFeatures.XmlFeature.JDK_OVERRIDE_PARSER);
+                        reader = JdkXmlUtils.getXMLReader(overrideDefaultParser,
+                                xsltc.isSecureProcessing());
+                    } else {
+                        // compatibility for legacy applications
+                        reader.setFeature
+                            (JdkXmlUtils.NAMESPACES_FEATURE,true);
+                        reader.setFeature
+                            (JdkXmlUtils.NAMESPACE_PREFIXES_FEATURE,false);
                     }
-                    reader.setFeature
-                        ("http://xml.org/sax/features/namespaces",true);
-                    reader.setFeature
-                        ("http://xml.org/sax/features/namespace-prefixes",false);
 
                     JdkXmlUtils.setXMLReaderPropertyIfSupport(reader, XMLConstants.ACCESS_EXTERNAL_DTD,
                             xsltc.getProperty(XMLConstants.ACCESS_EXTERNAL_DTD), true);
@@ -192,9 +154,6 @@
                 }catch (SAXNotSupportedException snse ) {
                   throw new TransformerConfigurationException
                        ("SAXNotSupportedException ",snse);
-                }catch (SAXException se ) {
-                  throw new TransformerConfigurationException
-                       ("SAXException ",se);
                 }
 
             }
--- a/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/dom/DOMConfigurationImpl.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/dom/DOMConfigurationImpl.java	Fri Jan 12 15:05:35 2018 -0800
@@ -259,7 +259,8 @@
             SEND_PSVI,
             NAMESPACE_GROWTH,
             TOLERATE_DUPLICATES,
-            XMLConstants.USE_CATALOG
+            XMLConstants.USE_CATALOG,
+            JdkXmlUtils.OVERRIDE_PARSER
         };
         addRecognizedFeatures(recognizedFeatures);
 
@@ -273,6 +274,7 @@
         setFeature(SEND_PSVI, true);
         setFeature(NAMESPACE_GROWTH, false);
         setFeature(XMLConstants.USE_CATALOG, JdkXmlUtils.USE_CATALOG_DEFAULT);
+        setFeature(JdkXmlUtils.OVERRIDE_PARSER, JdkXmlUtils.OVERRIDE_PARSER_DEFAULT);
 
         // add default recognized properties
         final String[] recognizedProperties = {
--- a/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XMLSchemaLoader.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XMLSchemaLoader.java	Fri Jan 12 15:05:35 2018 -0800
@@ -75,6 +75,7 @@
 import java.util.StringTokenizer;
 import java.util.WeakHashMap;
 import javax.xml.XMLConstants;
+import jdk.xml.internal.JdkXmlFeatures;
 import jdk.xml.internal.JdkXmlUtils;
 import jdk.xml.internal.SecuritySupport;
 import org.w3c.dom.DOMConfiguration;
@@ -160,7 +161,7 @@
     protected static final String SCHEMA_DV_FACTORY =
         Constants.XERCES_PROPERTY_PREFIX + Constants.SCHEMA_DV_FACTORY_PROPERTY;
 
-    protected static final String USE_SERVICE_MECHANISM = Constants.ORACLE_FEATURE_SERVICE_MECHANISM;
+    protected static final String OVERRIDE_PARSER = JdkXmlUtils.OVERRIDE_PARSER;
 
     // recognized features:
     private static final String[] RECOGNIZED_FEATURES = {
@@ -175,7 +176,7 @@
         HONOUR_ALL_SCHEMALOCATIONS,
         NAMESPACE_GROWTH,
         TOLERATE_DUPLICATES,
-        USE_SERVICE_MECHANISM,
+        OVERRIDE_PARSER,
         XMLConstants.USE_CATALOG
     };
 
@@ -313,18 +314,14 @@
      * @param sHandler
      * @param builder
      */
-    XMLSchemaLoader(XMLErrorReporter errorReporter,
-            XSGrammarBucket grammarBucket,
+    XMLSchemaLoader(XMLErrorReporter errorReporter, XSGrammarBucket grammarBucket,
             SubstitutionGroupHandler sHandler, CMBuilder builder) {
         this(null, errorReporter, null, grammarBucket, sHandler, builder);
     }
 
-    XMLSchemaLoader(SymbolTable symbolTable,
-            XMLErrorReporter errorReporter,
-            XMLEntityManager entityResolver,
-            XSGrammarBucket grammarBucket,
-            SubstitutionGroupHandler sHandler,
-            CMBuilder builder) {
+    XMLSchemaLoader(SymbolTable symbolTable, XMLErrorReporter errorReporter,
+            XMLEntityManager entityResolver, XSGrammarBucket grammarBucket,
+            SubstitutionGroupHandler sHandler, CMBuilder builder) {
 
         // store properties and features in configuration
         fLoaderConfig.addRecognizedFeatures(RECOGNIZED_FEATURES);
@@ -1231,7 +1228,7 @@
                 name.equals(HONOUR_ALL_SCHEMALOCATIONS) ||
                 name.equals(NAMESPACE_GROWTH) ||
                 name.equals(TOLERATE_DUPLICATES) ||
-                name.equals(USE_SERVICE_MECHANISM)) {
+                name.equals(OVERRIDE_PARSER)) {
                 return true;
 
             }
@@ -1310,7 +1307,7 @@
             v.add(HONOUR_ALL_SCHEMALOCATIONS);
             v.add(NAMESPACE_GROWTH);
             v.add(TOLERATE_DUPLICATES);
-            v.add(USE_SERVICE_MECHANISM);
+            v.add(OVERRIDE_PARSER);
             fRecognizedParameters = new DOMStringListImpl(v);
         }
         return fRecognizedParameters;
--- a/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XMLSchemaValidator.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XMLSchemaValidator.java	Fri Jan 12 15:05:35 2018 -0800
@@ -265,7 +265,7 @@
     private static final String XML_SECURITY_PROPERTY_MANAGER =
             Constants.XML_SECURITY_PROPERTY_MANAGER;
 
-    protected static final String USE_SERVICE_MECHANISM = Constants.ORACLE_FEATURE_SERVICE_MECHANISM;
+    protected static final String OVERRIDE_PARSER = JdkXmlUtils.OVERRIDE_PARSER;
 
     protected static final String USE_CATALOG = XMLConstants.USE_CATALOG;
 
@@ -291,8 +291,8 @@
             UNPARSED_ENTITY_CHECKING,
             NAMESPACE_GROWTH,
             TOLERATE_DUPLICATES,
-            USE_SERVICE_MECHANISM,
-            USE_CATALOG
+            OVERRIDE_PARSER,
+            USE_CATALOG,
         };
 
     /** Feature defaults. */
@@ -323,7 +323,7 @@
         null,
         null,
         null,
-        Boolean.TRUE,
+        JdkXmlUtils.OVERRIDE_PARSER_DEFAULT,
         JdkXmlUtils.USE_CATALOG_DEFAULT
     };
 
--- a/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/opti/SchemaParsingConfig.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/opti/SchemaParsingConfig.java	Fri Jan 12 15:05:35 2018 -0800
@@ -304,7 +304,8 @@
             ALLOW_JAVA_ENCODINGS,       CONTINUE_AFTER_FATAL_ERROR,
             LOAD_EXTERNAL_DTD,          NOTIFY_BUILTIN_REFS,
             NOTIFY_CHAR_REFS, GENERATE_SYNTHETIC_ANNOTATIONS,
-            XMLConstants.USE_CATALOG
+            XMLConstants.USE_CATALOG,
+            JdkXmlUtils.OVERRIDE_PARSER
         };
         addRecognizedFeatures(recognizedFeatures);
         fFeatures.put(PARSER_SETTINGS, Boolean.TRUE);
@@ -319,6 +320,7 @@
         fFeatures.put(NOTIFY_CHAR_REFS, Boolean.FALSE);
         fFeatures.put(GENERATE_SYNTHETIC_ANNOTATIONS, Boolean.FALSE);
         fFeatures.put(XMLConstants.USE_CATALOG, JdkXmlUtils.USE_CATALOG_DEFAULT);
+        fFeatures.put(JdkXmlUtils.OVERRIDE_PARSER, JdkXmlUtils.OVERRIDE_PARSER_DEFAULT);
 
         // add default recognized properties
         final String[] recognizedProperties = {
--- a/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/traversers/XSDHandler.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/traversers/XSDHandler.java	Fri Jan 12 15:05:35 2018 -0800
@@ -115,7 +115,6 @@
 import org.xml.sax.SAXNotRecognizedException;
 import org.xml.sax.SAXParseException;
 import org.xml.sax.XMLReader;
-import org.xml.sax.helpers.XMLReaderFactory;
 
 /**
  * The purpose of this class is to co-ordinate the construction of a
@@ -422,6 +421,8 @@
     private String fPrefer;
     private String fResolve;
 
+    private boolean fOverrideDefaultParser;
+
     //************ Traversers **********
     XSDAttributeGroupTraverser fAttributeGroupTraverser;
     XSDAttributeTraverser fAttributeTraverser;
@@ -2244,7 +2245,8 @@
                 XSDKey key = null;
                 String schemaId = null;
                 if (referType != XSDDescription.CONTEXT_PREPARSE) {
-                    schemaId = XMLEntityManager.expandSystemId(inputSource.getSystemId(), schemaSource.getBaseSystemId(), false);
+                    schemaId = XMLEntityManager.expandSystemId(inputSource.getSystemId(),
+                            schemaSource.getBaseSystemId(), false);
                     key = new XSDKey(schemaId, referType, schemaNamespace);
                     if ((schemaElement = fTraversed.get(key)) != null) {
                         fLastSchemaWasDuplicate = true;
@@ -2260,17 +2262,10 @@
                     catch (SAXException se) {}
                 }
                 else {
+                    parser = JdkXmlUtils.getXMLReader(fOverrideDefaultParser,
+                            fSecurityManager.isSecureProcessing());
+
                     try {
-                        parser = XMLReaderFactory.createXMLReader();
-                    }
-                    // If something went wrong with the factory
-                    // just use our own SAX parser.
-                    catch (SAXException se) {
-                        parser = new SAXParser();
-                    }
-                    try {
-                        parser.setFeature(NAMESPACE_PREFIXES, true);
-                        namespacePrefixes = true;
                         // If this is a Xerces SAX parser set the security manager if there is one
                         if (parser instanceof SAXParser) {
                             if (fSecurityManager != null) {
@@ -3629,6 +3624,9 @@
         fAccessExternalSchema = fSecurityPropertyMgr.getValue(
                 XMLSecurityPropertyManager.Property.ACCESS_EXTERNAL_SCHEMA);
 
+        fOverrideDefaultParser = componentManager.getFeature(JdkXmlUtils.OVERRIDE_PARSER);
+        fSchemaParser.setFeature(JdkXmlUtils.OVERRIDE_PARSER, fOverrideDefaultParser);
+        fEntityManager.setFeature(JdkXmlUtils.OVERRIDE_PARSER, fOverrideDefaultParser);
         // Passing the Catalog settings to the parser
         fUseCatalog = componentManager.getFeature(XMLConstants.USE_CATALOG);
         fSchemaParser.setFeature(XMLConstants.USE_CATALOG, fUseCatalog);
--- a/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/jaxp/validation/DOMValidatorHelper.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/jaxp/validation/DOMValidatorHelper.java	Fri Jan 12 15:05:35 2018 -0800
@@ -45,6 +45,7 @@
 import javax.xml.transform.Source;
 import javax.xml.transform.dom.DOMResult;
 import javax.xml.transform.dom.DOMSource;
+import jdk.xml.internal.JdkXmlUtils;
 import org.w3c.dom.Attr;
 import org.w3c.dom.CDATASection;
 import org.w3c.dom.Comment;
@@ -380,9 +381,8 @@
         }
         if (result.getNode() == null) {
             try {
-                DocumentBuilderFactory factory = fComponentManager.getFeature(Constants.ORACLE_FEATURE_SERVICE_MECHANISM) ?
-                                    DocumentBuilderFactory.newInstance() : new DocumentBuilderFactoryImpl();
-                factory.setNamespaceAware(true);
+                DocumentBuilderFactory factory = JdkXmlUtils.getDOMFactory(
+                        fComponentManager.getFeature(JdkXmlUtils.OVERRIDE_PARSER));
                 DocumentBuilder builder = factory.newDocumentBuilder();
                 result.setNode(builder.newDocument());
             }
--- a/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/jaxp/validation/StAXValidatorHelper.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/jaxp/validation/StAXValidatorHelper.java	Fri Jan 12 15:05:35 2018 -0800
@@ -25,6 +25,7 @@
 
 package com.sun.org.apache.xerces.internal.jaxp.validation;
 
+import com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl;
 import com.sun.org.apache.xerces.internal.impl.Constants;
 import com.sun.org.apache.xerces.internal.utils.XMLSecurityManager;
 import java.io.IOException;
@@ -41,6 +42,7 @@
 import javax.xml.transform.sax.TransformerHandler;
 import javax.xml.transform.stax.StAXResult;
 import javax.xml.transform.stax.StAXSource;
+import jdk.xml.internal.JdkXmlUtils;
 
 import org.xml.sax.SAXException;
 
@@ -50,7 +52,6 @@
  * @author Sunitha Reddy
  */
 public final class StAXValidatorHelper implements ValidatorHelper {
-    private static final String DEFAULT_TRANSFORMER_IMPL = "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl";
 
     /** Component manager. **/
     private XMLSchemaValidatorComponentManager fComponentManager;
@@ -71,10 +72,11 @@
 
             if( identityTransformer1==null ) {
                 try {
-                    SAXTransformerFactory tf = fComponentManager.getFeature(Constants.ORACLE_FEATURE_SERVICE_MECHANISM) ?
-                                    (SAXTransformerFactory)SAXTransformerFactory.newInstance()
-                                    : (SAXTransformerFactory) TransformerFactory.newInstance(DEFAULT_TRANSFORMER_IMPL, StAXValidatorHelper.class.getClassLoader());
-                    XMLSecurityManager securityManager = (XMLSecurityManager)fComponentManager.getProperty(Constants.SECURITY_MANAGER);
+                    SAXTransformerFactory tf = JdkXmlUtils.getSAXTransformFactory(
+                            fComponentManager.getFeature(JdkXmlUtils.OVERRIDE_PARSER));
+
+                    XMLSecurityManager securityManager =
+                            (XMLSecurityManager)fComponentManager.getProperty(Constants.SECURITY_MANAGER);
                     if (securityManager != null) {
                         for (XMLSecurityManager.Limit limit : XMLSecurityManager.Limit.values()) {
                             if (securityManager.isSet(limit.ordinal())){
--- a/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/jaxp/validation/StreamValidatorHelper.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/jaxp/validation/StreamValidatorHelper.java	Fri Jan 12 15:05:35 2018 -0800
@@ -98,9 +98,6 @@
     private static final String VALIDATION_MANAGER
             = Constants.XERCES_PROPERTY_PREFIX + Constants.VALIDATION_MANAGER_PROPERTY;
 
-    private static final String DEFAULT_TRANSFORMER_IMPL
-            = "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl";
-
     /**
      * Property id: security manager.
      */
@@ -141,12 +138,9 @@
 
             if (result != null) {
                 try {
-                    SAXTransformerFactory tf = fComponentManager.getFeature(
-                            Constants.ORACLE_FEATURE_SERVICE_MECHANISM) ?
-                            (SAXTransformerFactory) SAXTransformerFactory.newInstance() :
-                            (SAXTransformerFactory) TransformerFactory.newInstance(
-                                    DEFAULT_TRANSFORMER_IMPL,
-                                    StreamValidatorHelper.class.getClassLoader());
+                    SAXTransformerFactory tf = JdkXmlUtils.getSAXTransformFactory(
+                            fComponentManager.getFeature(JdkXmlUtils.OVERRIDE_PARSER));
+
                     identityTransformerHandler = tf.newTransformerHandler();
                 } catch (TransformerConfigurationException e) {
                     throw new TransformerFactoryConfigurationError(e);
--- a/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/jaxp/validation/ValidatorHandlerImpl.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/jaxp/validation/ValidatorHandlerImpl.java	Fri Jan 12 15:05:35 2018 -0800
@@ -675,16 +675,14 @@
                 XMLReader reader = saxSource.getXMLReader();
                 if( reader==null ) {
                     // create one now
-                    SAXParserFactory spf = fComponentManager.getFeature(Constants.ORACLE_FEATURE_SERVICE_MECHANISM) ?
-                                    SAXParserFactory.newInstance() : new SAXParserFactoryImpl();
-                    spf.setNamespaceAware(true);
+                    reader = JdkXmlUtils.getXMLReader(fComponentManager.getFeature(JdkXmlUtils.OVERRIDE_PARSER),
+                            fComponentManager.getFeature(XMLConstants.FEATURE_SECURE_PROCESSING));
+
                     try {
-                        spf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING,
-                                fComponentManager.getFeature(XMLConstants.FEATURE_SECURE_PROCESSING));
-                        reader = spf.newSAXParser().getXMLReader();
                         // If this is a Xerces SAX parser, set the security manager if there is one
                         if (reader instanceof com.sun.org.apache.xerces.internal.parsers.SAXParser) {
-                           XMLSecurityManager securityManager = (XMLSecurityManager) fComponentManager.getProperty(SECURITY_MANAGER);
+                           XMLSecurityManager securityManager =
+                                   (XMLSecurityManager) fComponentManager.getProperty(SECURITY_MANAGER);
                            if (securityManager != null) {
                                try {
                                    reader.setProperty(SECURITY_MANAGER, securityManager);
--- a/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/jaxp/validation/XMLSchemaFactory.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/jaxp/validation/XMLSchemaFactory.java	Fri Jan 12 15:05:35 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2017, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * Licensed to the Apache Software Foundation (ASF) under one or more
@@ -51,6 +51,7 @@
 import javax.xml.transform.stream.StreamSource;
 import javax.xml.validation.Schema;
 import javax.xml.validation.SchemaFactory;
+import jdk.xml.internal.JdkXmlFeatures;
 import jdk.xml.internal.JdkXmlUtils;
 import org.w3c.dom.Node;
 import org.w3c.dom.ls.LSResourceResolver;
@@ -127,22 +128,16 @@
     /** Whether or not to allow new schemas to be added to the grammar pool */
     private boolean fUseGrammarPoolOnly;
 
+    private final JdkXmlFeatures fXmlFeatures;
     /**
-     * Indicates whether implementation parts should use
-     *   service loader (or similar).
-     * Note the default value (false) is the safe option..
+     * Indicates whether 3rd party parser may be used to override the system-default
+     * Note the default value (false) is the safe option.
+     * Note same as the old property useServicesMechanism
      */
-    private final boolean fUseServicesMechanism;
+    private final boolean fOverrideDefaultParser;
 
 
     public XMLSchemaFactory() {
-        this(true);
-    }
-    public static XMLSchemaFactory newXMLSchemaFactoryNoServiceLoader() {
-        return new XMLSchemaFactory(false);
-    }
-    private XMLSchemaFactory(boolean useServicesMechanism) {
-        fUseServicesMechanism = useServicesMechanism;
         fErrorHandlerWrapper = new ErrorHandlerWrapper(DraconianErrorHandler.getInstance());
         fDOMEntityResolverWrapper = new DOMEntityResolverWrapper();
         fXMLGrammarPoolWrapper = new XMLGrammarPoolWrapper();
@@ -167,6 +162,10 @@
         }
 
         fXMLSchemaLoader.setProperty(JdkXmlUtils.CDATA_CHUNK_SIZE, JdkXmlUtils.CDATA_CHUNK_SIZE_DEFAULT);
+        fXmlFeatures = new JdkXmlFeatures(fSecurityManager.isSecureProcessing());
+        fOverrideDefaultParser = fXmlFeatures.getFeature(
+                JdkXmlFeatures.XmlFeature.JDK_OVERRIDE_PARSER);
+        fXMLSchemaLoader.setFeature(JdkXmlUtils.OVERRIDE_PARSER, fOverrideDefaultParser);
     }
 
     /**
@@ -363,6 +362,11 @@
         else if (name.equals(USE_GRAMMAR_POOL_ONLY)) {
             return fUseGrammarPoolOnly;
         }
+        /** Check to see if the property is managed by the JdkXmlFeatues **/
+        int index = fXmlFeatures.getIndex(name);
+        if (index > -1) {
+            return fXmlFeatures.getFeature(index);
+        }
         try {
             return fXMLSchemaLoader.getFeature(name);
         }
@@ -452,10 +456,20 @@
             return;
         }
         else if (name.equals(Constants.ORACLE_FEATURE_SERVICE_MECHANISM)) {
-            //in secure mode, let _useServicesMechanism be determined by the constructor
+            //in secure mode, let useServicesMechanism be determined by the constructor
             if (System.getSecurityManager() != null)
                 return;
         }
+
+        if ((fXmlFeatures != null) &&
+                    fXmlFeatures.setFeature(name, JdkXmlFeatures.State.APIPROPERTY, value)) {
+            if (name.equals(JdkXmlUtils.OVERRIDE_PARSER)
+                    || name.equals(Constants.ORACLE_FEATURE_SERVICE_MECHANISM)
+                    || name.equals(JdkXmlUtils.USE_CATALOG)) {
+                fXMLSchemaLoader.setFeature(name, value);
+            }
+            return;
+        }
         try {
             fXMLSchemaLoader.setFeature(name, value);
         }
@@ -528,7 +542,7 @@
     private void propagateFeatures(AbstractXMLSchema schema) {
         schema.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING,
                 (fSecurityManager != null && fSecurityManager.isSecureProcessing()));
-        schema.setFeature(Constants.ORACLE_FEATURE_SERVICE_MECHANISM, fUseServicesMechanism);
+        schema.setFeature(JdkXmlUtils.OVERRIDE_PARSER, fOverrideDefaultParser);
         String[] features = fXMLSchemaLoader.getRecognizedFeatures();
         for (int i = 0; i < features.length; ++i) {
             boolean state = fXMLSchemaLoader.getFeature(features[i]);
--- a/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/jaxp/validation/XMLSchemaValidatorComponentManager.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/jaxp/validation/XMLSchemaValidatorComponentManager.java	Fri Jan 12 15:05:35 2018 -0800
@@ -264,7 +264,8 @@
                 NORMALIZE_DATA,
                 SCHEMA_ELEMENT_DEFAULT,
                 SCHEMA_AUGMENT_PSVI,
-                XMLConstants.USE_CATALOG
+                XMLConstants.USE_CATALOG,
+                JdkXmlUtils.OVERRIDE_PARSER
         };
         addRecognizedFeatures(recognizedFeatures);
         fFeatures.put(DISALLOW_DOCTYPE_DECL_FEATURE, Boolean.FALSE);
@@ -272,6 +273,7 @@
         fFeatures.put(SCHEMA_ELEMENT_DEFAULT, Boolean.FALSE);
         fFeatures.put(SCHEMA_AUGMENT_PSVI, Boolean.TRUE);
         fFeatures.put(XMLConstants.USE_CATALOG, grammarContainer.getFeature(XMLConstants.USE_CATALOG));
+        fFeatures.put(JdkXmlUtils.OVERRIDE_PARSER, grammarContainer.getFeature(JdkXmlUtils.OVERRIDE_PARSER));
 
         addRecognizedParamsAndSetDefaults(fEntityManager, grammarContainer);
         addRecognizedParamsAndSetDefaults(fErrorReporter, grammarContainer);
--- a/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/parsers/DTDConfiguration.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/parsers/DTDConfiguration.java	Fri Jan 12 15:05:35 2018 -0800
@@ -310,7 +310,8 @@
             //NOTIFY_BUILTIN_REFS,  // from XMLDocumentFragmentScannerImpl
             //NOTIFY_CHAR_REFS,         // from XMLDocumentFragmentScannerImpl
             //WARN_ON_DUPLICATE_ENTITYDEF,  // from XMLEntityManager
-            XMLConstants.USE_CATALOG
+            XMLConstants.USE_CATALOG,
+            JdkXmlUtils.OVERRIDE_PARSER
         };
         addRecognizedFeatures(recognizedFeatures);
 
@@ -324,6 +325,7 @@
         //setFeature(NOTIFY_CHAR_REFS, false);      // from XMLDocumentFragmentScannerImpl
         //setFeature(WARN_ON_DUPLICATE_ENTITYDEF, false);   // from XMLEntityManager
         fFeatures.put(XMLConstants.USE_CATALOG, JdkXmlUtils.USE_CATALOG_DEFAULT);
+        fFeatures.put(JdkXmlUtils.OVERRIDE_PARSER, JdkXmlUtils.OVERRIDE_PARSER_DEFAULT);
 
         // add default recognized properties
         final String[] recognizedProperties = {
--- a/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/parsers/NonValidatingConfiguration.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/parsers/NonValidatingConfiguration.java	Fri Jan 12 15:05:35 2018 -0800
@@ -294,7 +294,8 @@
             //NOTIFY_BUILTIN_REFS,  // from XMLDocumentFragmentScannerImpl
             //NOTIFY_CHAR_REFS,         // from XMLDocumentFragmentScannerImpl
             //WARN_ON_DUPLICATE_ENTITYDEF   // from XMLEntityManager
-            XMLConstants.USE_CATALOG
+            XMLConstants.USE_CATALOG,
+            JdkXmlUtils.OVERRIDE_PARSER
         };
         addRecognizedFeatures(recognizedFeatures);
 
@@ -310,6 +311,7 @@
         //setFeature(NOTIFY_CHAR_REFS, false);      // from XMLDocumentFragmentScannerImpl
         //setFeature(WARN_ON_DUPLICATE_ENTITYDEF, false);   // from XMLEntityManager
         fFeatures.put(XMLConstants.USE_CATALOG, JdkXmlUtils.USE_CATALOG_DEFAULT);
+        fFeatures.put(JdkXmlUtils.OVERRIDE_PARSER, JdkXmlUtils.OVERRIDE_PARSER_DEFAULT);
 
         // add default recognized properties
         final String[] recognizedProperties = {
--- a/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/parsers/XML11Configuration.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/parsers/XML11Configuration.java	Fri Jan 12 15:05:35 2018 -0800
@@ -508,7 +508,8 @@
             PARSER_SETTINGS,
             XMLConstants.FEATURE_SECURE_PROCESSING,
             XMLConstants.USE_CATALOG,
-            JdkXmlUtils.RESET_SYMBOL_TABLE
+            JdkXmlUtils.RESET_SYMBOL_TABLE,
+            JdkXmlUtils.OVERRIDE_PARSER
         };
         addRecognizedFeatures(recognizedFeatures);
         // set state for default features
@@ -535,6 +536,7 @@
         fFeatures.put(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
         fFeatures.put(XMLConstants.USE_CATALOG, JdkXmlUtils.USE_CATALOG_DEFAULT);
         fFeatures.put(JdkXmlUtils.RESET_SYMBOL_TABLE, JdkXmlUtils.RESET_SYMBOL_TABLE_DEFAULT);
+        fFeatures.put(JdkXmlUtils.OVERRIDE_PARSER, JdkXmlUtils.OVERRIDE_PARSER_DEFAULT);
 
         // add default recognized properties
         final String[] recognizedProperties =
--- a/src/java.xml/share/classes/com/sun/org/apache/xml/internal/dtm/DTMManager.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.xml/share/classes/com/sun/org/apache/xml/internal/dtm/DTMManager.java	Fri Jan 12 15:05:35 2018 -0800
@@ -52,7 +52,7 @@
    */
   protected XMLStringFactory m_xsf = null;
 
-  private boolean _useServicesMechanism;
+  private boolean _overrideDefaultParser;
   /**
    * Default constructor is protected on purpose.
    */
@@ -297,15 +297,15 @@
     /**
      * Return the state of the services mechanism feature.
      */
-    public boolean useServicesMechnism() {
-        return _useServicesMechanism;
+    public boolean overrideDefaultParser() {
+        return _overrideDefaultParser;
     }
 
     /**
      * Set the state of the services mechanism feature.
      */
-    public void setServicesMechnism(boolean flag) {
-        _useServicesMechanism = flag;
+    public void setOverrideDefaultParser(boolean flag) {
+        _overrideDefaultParser = flag;
     }
 
   // -------------------- private methods --------------------
--- a/src/java.xml/share/classes/com/sun/org/apache/xml/internal/dtm/ref/DTMManagerDefault.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.xml/share/classes/com/sun/org/apache/xml/internal/dtm/ref/DTMManagerDefault.java	Fri Jan 12 15:05:35 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2017, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * Licensed to the Apache Software Foundation (ASF) under one or more
@@ -20,7 +20,6 @@
 
 package com.sun.org.apache.xml.internal.dtm.ref;
 
-import com.sun.org.apache.xalan.internal.utils.FactoryImpl;
 import javax.xml.parsers.DocumentBuilder;
 import javax.xml.parsers.DocumentBuilderFactory;
 import javax.xml.transform.Source;
@@ -43,6 +42,7 @@
 import com.sun.org.apache.xml.internal.utils.SystemIDResolver;
 import com.sun.org.apache.xml.internal.utils.XMLReaderManager;
 import com.sun.org.apache.xml.internal.utils.XMLStringFactory;
+import jdk.xml.internal.JdkXmlUtils;
 
 import org.w3c.dom.Document;
 import org.w3c.dom.Node;
@@ -606,7 +606,7 @@
       // If user did not supply a reader, ask for one from the reader manager
       if (null == reader) {
         if (m_readerManager == null) {
-            m_readerManager = XMLReaderManager.getInstance(super.useServicesMechnism());
+            m_readerManager = XMLReaderManager.getInstance(super.overrideDefaultParser());
         }
 
         reader = m_readerManager.getXMLReader();
@@ -765,8 +765,7 @@
 
     try
     {
-      DocumentBuilderFactory dbf = FactoryImpl.getDOMFactory(super.useServicesMechnism());
-      dbf.setNamespaceAware(true);
+      DocumentBuilderFactory dbf = JdkXmlUtils.getDOMFactory(super.overrideDefaultParser());
 
       DocumentBuilder db = dbf.newDocumentBuilder();
       Document doc = db.newDocument();
--- a/src/java.xml/share/classes/com/sun/org/apache/xml/internal/utils/AttList.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.xml/share/classes/com/sun/org/apache/xml/internal/utils/AttList.java	Fri Jan 12 15:05:35 2018 -0800
@@ -45,9 +45,7 @@
   /**
    * Constructor AttList
    *
-   *
    * @param attrs List of attributes this will contain
-   * @param dh DOMHelper
    */
   public AttList(NamedNodeMap attrs)
   {
--- a/src/java.xml/share/classes/com/sun/org/apache/xml/internal/utils/XMLReaderManager.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.xml/share/classes/com/sun/org/apache/xml/internal/utils/XMLReaderManager.java	Fri Jan 12 15:05:35 2018 -0800
@@ -21,14 +21,10 @@
 package com.sun.org.apache.xml.internal.utils;
 
 import com.sun.org.apache.xalan.internal.XalanConstants;
-import com.sun.org.apache.xalan.internal.utils.FactoryImpl;
 import com.sun.org.apache.xalan.internal.utils.XMLSecurityManager;
 import java.util.HashMap;
 import javax.xml.XMLConstants;
 import javax.xml.catalog.CatalogFeatures;
-import javax.xml.parsers.FactoryConfigurationError;
-import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.parsers.SAXParserFactory;
 import jdk.xml.internal.JdkXmlFeatures;
 import jdk.xml.internal.JdkXmlUtils;
 import jdk.xml.internal.SecuritySupport;
@@ -36,7 +32,6 @@
 import org.xml.sax.SAXNotRecognizedException;
 import org.xml.sax.SAXNotSupportedException;
 import org.xml.sax.XMLReader;
-import org.xml.sax.helpers.XMLReaderFactory;
 
 /**
  * Creates XMLReader objects and caches them for re-use.
@@ -44,32 +39,23 @@
  *
  * @LastModified: Sep 2017
  */
-@SuppressWarnings("deprecation") //org.xml.sax.helpers.XMLReaderFactory
 public class XMLReaderManager {
 
-    private static final String NAMESPACES_FEATURE =
-                             "http://xml.org/sax/features/namespaces";
-    private static final String NAMESPACE_PREFIXES_FEATURE =
-                             "http://xml.org/sax/features/namespace-prefixes";
     private static final XMLReaderManager m_singletonManager =
                                                      new XMLReaderManager();
     private static final String property = "org.xml.sax.driver";
-    /**
-     * Parser factory to be used to construct XMLReader objects
-     */
-    private static SAXParserFactory m_parserFactory;
 
     /**
      * Cache of XMLReader objects
      */
-    private ThreadLocal<XMLReader> m_readers;
+    private ThreadLocal<ReaderWrapper> m_readers;
 
     /**
      * Keeps track of whether an XMLReader object is in use.
      */
     private HashMap<XMLReader, Boolean> m_inUse;
 
-    private boolean m_useServicesMechanism = true;
+    private boolean m_overrideDefaultParser;
 
     private boolean _secureProcessing;
      /**
@@ -94,8 +80,8 @@
     /**
      * Retrieves the singleton reader manager
      */
-    public static XMLReaderManager getInstance(boolean useServicesMechanism) {
-        m_singletonManager.setServicesMechnism(useServicesMechanism);
+    public static XMLReaderManager getInstance(boolean overrideDefaultParser) {
+        m_singletonManager.setOverrideDefaultParser(overrideDefaultParser);
         return m_singletonManager;
     }
 
@@ -118,61 +104,30 @@
             m_inUse = new HashMap<>();
         }
 
-        // If the cached reader for this thread is in use, construct a new
-        // one; otherwise, return the cached reader unless it isn't an
-        // instance of the class set in the 'org.xml.sax.driver' property
-        reader = m_readers.get();
-        boolean threadHasReader = (reader != null);
+        /**
+         * Constructs a new XMLReader if:
+         * (1) the cached reader for this thread is in use, or
+         * (2) the requirement for overriding has changed,
+         * (3) the cached reader isn't an instance of the class set in the
+         * 'org.xml.sax.driver' property
+         *
+         * otherwise, returns the cached reader
+         */
+        ReaderWrapper rw = m_readers.get();
+        boolean threadHasReader = (rw != null);
+        reader = threadHasReader ? rw.reader : null;
         String factory = SecuritySupport.getSystemProperty(property);
         if (threadHasReader && m_inUse.get(reader) != Boolean.TRUE &&
+                (rw.overrideDefaultParser == m_overrideDefaultParser) &&
                 ( factory == null || reader.getClass().getName().equals(factory))) {
             m_inUse.put(reader, Boolean.TRUE);
         } else {
-            try {
-                try {
-                    // According to JAXP 1.2 specification, if a SAXSource
-                    // is created using a SAX InputSource the Transformer or
-                    // TransformerFactory creates a reader via the
-                    // XMLReaderFactory if setXMLReader is not used
-                    reader = XMLReaderFactory.createXMLReader();
-                    try {
-                        reader.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, _secureProcessing);
-                    } catch (SAXNotRecognizedException e) {
-                        XMLSecurityManager.printWarning(reader.getClass().getName(),
-                                XMLConstants.FEATURE_SECURE_PROCESSING, e);
-                    }
-                } catch (SAXException e) {
-                   try {
-                        // If unable to create an instance, let's try to use
-                        // the XMLReader from JAXP
-                        if (m_parserFactory == null) {
-                            m_parserFactory = FactoryImpl.getSAXFactory(m_useServicesMechanism);
-                            m_parserFactory.setNamespaceAware(true);
-                        }
-
-                        reader = m_parserFactory.newSAXParser().getXMLReader();
-                   } catch (ParserConfigurationException pce) {
-                       throw pce;   // pass along pce
-                   }
-                }
-                try {
-                    reader.setFeature(NAMESPACES_FEATURE, true);
-                    reader.setFeature(NAMESPACE_PREFIXES_FEATURE, false);
-                } catch (SAXException se) {
-                    // Try to carry on if we've got a parser that
-                    // doesn't know about namespace prefixes.
-                }
-            } catch (ParserConfigurationException ex) {
-                throw new SAXException(ex);
-            } catch (FactoryConfigurationError ex1) {
-                throw new SAXException(ex1.toString());
-            } catch (NoSuchMethodError | AbstractMethodError ex2) {
-            }
+            reader = JdkXmlUtils.getXMLReader(m_overrideDefaultParser, _secureProcessing);
 
             // Cache the XMLReader if this is the first time we've created
             // a reader for this thread.
             if (!threadHasReader) {
-                m_readers.set(reader);
+                m_readers.set(new ReaderWrapper(reader, m_overrideDefaultParser));
                 m_inUse.put(reader, Boolean.TRUE);
             }
         }
@@ -230,22 +185,23 @@
     public synchronized void releaseXMLReader(XMLReader reader) {
         // If the reader that's being released is the cached reader
         // for this thread, remove it from the m_isUse list.
-        if (m_readers.get() == reader && reader != null) {
+        ReaderWrapper rw = m_readers.get();
+        if (rw.reader == reader && reader != null) {
             m_inUse.remove(reader);
         }
     }
     /**
      * Return the state of the services mechanism feature.
      */
-    public boolean useServicesMechnism() {
-        return m_useServicesMechanism;
+    public boolean overrideDefaultParser() {
+        return m_overrideDefaultParser;
     }
 
     /**
      * Set the state of the services mechanism feature.
      */
-    public void setServicesMechnism(boolean flag) {
-        m_useServicesMechanism = flag;
+    public void setOverrideDefaultParser(boolean flag) {
+        m_overrideDefaultParser = flag;
     }
 
     /**
@@ -285,4 +241,14 @@
             _cdataChunkSize = JdkXmlUtils.getValue(value, _cdataChunkSize);
         }
     }
+
+    class ReaderWrapper {
+        XMLReader reader;
+        boolean overrideDefaultParser;
+
+        public ReaderWrapper(XMLReader reader, boolean overrideDefaultParser) {
+            this.reader = reader;
+            this.overrideDefaultParser = overrideDefaultParser;
+        }
+    }
 }
--- a/src/java.xml/share/classes/com/sun/org/apache/xpath/internal/CachedXPathAPI.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.xml/share/classes/com/sun/org/apache/xpath/internal/CachedXPathAPI.java	Fri Jan 12 15:05:35 2018 -0800
@@ -1,6 +1,5 @@
 /*
- * reserved comment block
- * DO NOT REMOVE OR ALTER!
+ * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * Licensed to the Apache Software Foundation (ASF) under one or more
@@ -26,6 +25,7 @@
 import com.sun.org.apache.xml.internal.utils.PrefixResolver;
 import com.sun.org.apache.xml.internal.utils.PrefixResolverDefault;
 import com.sun.org.apache.xpath.internal.objects.XObject;
+import jdk.xml.internal.JdkXmlUtils;
 
 import org.w3c.dom.Document;
 import org.w3c.dom.Node;
@@ -73,7 +73,7 @@
    */
   public CachedXPathAPI()
   {
-    xpathSupport = new XPathContext();
+    xpathSupport = new XPathContext(JdkXmlUtils.OVERRIDE_PARSER_DEFAULT);
   }
 
   /**
@@ -328,7 +328,7 @@
     XPath xpath = new XPath(str, null, prefixResolver, XPath.SELECT, null);
 
     // Execute the XPath, and have it return the result
-    XPathContext xpathSupport = new XPathContext();
+    XPathContext xpathSupport = new XPathContext(JdkXmlUtils.OVERRIDE_PARSER_DEFAULT);
     int ctxtNode = xpathSupport.getDTMHandleFromNode(contextNode);
 
     return xpath.execute(xpathSupport, ctxtNode, prefixResolver);
--- a/src/java.xml/share/classes/com/sun/org/apache/xpath/internal/XPathAPI.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.xml/share/classes/com/sun/org/apache/xpath/internal/XPathAPI.java	Fri Jan 12 15:05:35 2018 -0800
@@ -1,6 +1,5 @@
 /*
- * reserved comment block
- * DO NOT REMOVE OR ALTER!
+ * Copyright (c) 2011, 2017, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * Licensed to the Apache Software Foundation (ASF) under one or more
@@ -26,6 +25,7 @@
 import com.sun.org.apache.xml.internal.utils.PrefixResolver;
 import com.sun.org.apache.xml.internal.utils.PrefixResolverDefault;
 import com.sun.org.apache.xpath.internal.objects.XObject;
+import jdk.xml.internal.JdkXmlUtils;
 
 import org.w3c.dom.Document;
 import org.w3c.dom.Node;
@@ -221,7 +221,7 @@
     // (Changed from: XPathContext xpathSupport = new XPathContext();
     //    because XPathContext is weak in a number of areas... perhaps
     //    XPathContext should be done away with.)
-    XPathContext xpathSupport = new XPathContext();
+    XPathContext xpathSupport = new XPathContext(JdkXmlUtils.OVERRIDE_PARSER_DEFAULT);
 
     // Create an object to resolve namespace prefixes.
     // XPath namespaces are resolved from the input context node's document element
@@ -276,7 +276,7 @@
     XPath xpath = new XPath(str, null, prefixResolver, XPath.SELECT, null);
 
     // Execute the XPath, and have it return the result
-    XPathContext xpathSupport = new XPathContext();
+    XPathContext xpathSupport = new XPathContext(JdkXmlUtils.OVERRIDE_PARSER_DEFAULT);
     int ctxtNode = xpathSupport.getDTMHandleFromNode(contextNode);
 
     return xpath.execute(xpathSupport, ctxtNode, prefixResolver);
--- a/src/java.xml/share/classes/com/sun/org/apache/xpath/internal/XPathContext.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.xml/share/classes/com/sun/org/apache/xpath/internal/XPathContext.java	Fri Jan 12 15:05:35 2018 -0800
@@ -1,5 +1,6 @@
 /*
- * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2017, Oracle and/or its affiliates. All rights reserved.
+ * @LastModified: Oct 2017
  */
 /*
  * Licensed to the Apache Software Foundation (ASF) under one or more
@@ -49,6 +50,7 @@
 import javax.xml.transform.ErrorListener;
 import javax.xml.transform.SourceLocator;
 import javax.xml.transform.URIResolver;
+import jdk.xml.internal.JdkXmlUtils;
 import org.xml.sax.XMLReader;
 
 /**
@@ -92,7 +94,7 @@
    */
   private boolean m_isSecureProcessing = false;
 
-  private boolean m_useServicesMechanism = true;
+  private boolean m_overrideDefaultParser;
 
   /**
    * Though XPathContext context extends
@@ -305,11 +307,11 @@
    */
   public XPathContext()
   {
-    this(true);
+    this(false);
   }
 
-  public XPathContext(boolean useServicesMechanism) {
-      init(useServicesMechanism);
+  public XPathContext(boolean overrideDefaultParser) {
+      init(overrideDefaultParser);
   }
   /**
    **This constructor doesn't seem to be used anywhere -- huizhe wang**
@@ -324,15 +326,15 @@
       m_ownerGetErrorListener = m_owner.getClass().getMethod("getErrorListener", new Class<?>[] {});
     }
     catch (NoSuchMethodException nsme) {}
-    init(true);
+    init(false);
   }
 
-  private void init(boolean useServicesMechanism) {
+  private void init(boolean overrideDefaultParser) {
     m_prefixResolvers.push(null);
     m_currentNodes.push(DTM.NULL);
     m_currentExpressionNodes.push(DTM.NULL);
     m_saxLocations.push(null);
-    m_useServicesMechanism = useServicesMechanism;
+    m_overrideDefaultParser = overrideDefaultParser;
     m_dtmManager = DTMManager.newInstance(
                    com.sun.org.apache.xpath.internal.objects.XMLStringFactoryImpl.getFactory()
                    );
@@ -1082,15 +1084,15 @@
     /**
      * Return the state of the services mechanism feature.
      */
-    public boolean useServicesMechnism() {
-        return m_useServicesMechanism;
+    public boolean overrideDefaultParser() {
+        return m_overrideDefaultParser;
     }
 
     /**
      * Set the state of the services mechanism feature.
      */
-    public void setServicesMechnism(boolean flag) {
-        m_useServicesMechanism = flag;
+    public void setOverrideDefaultParser(boolean flag) {
+        m_overrideDefaultParser = flag;
     }
 
     /**
--- a/src/java.xml/share/classes/com/sun/org/apache/xpath/internal/jaxp/XPathExpressionImpl.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.xml/share/classes/com/sun/org/apache/xpath/internal/jaxp/XPathExpressionImpl.java	Fri Jan 12 15:05:35 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2017, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * Licensed to the Apache Software Foundation (ASF) under one or more
@@ -31,7 +31,6 @@
 import javax.xml.xpath.XPathVariableResolver;
 import jdk.xml.internal.JdkXmlFeatures;
 import org.w3c.dom.Document;
-import org.w3c.dom.Node;
 import org.xml.sax.InputSource;
 
 /**
@@ -47,8 +46,7 @@
      * from the context.
      */
     protected XPathExpressionImpl() {
-        this(null, null, null, null,
-             false, true, new JdkXmlFeatures(false));
+        this(null, null, null, null, false, new JdkXmlFeatures(false));
     };
 
     protected XPathExpressionImpl(com.sun.org.apache.xpath.internal.XPath xpath,
@@ -56,19 +54,20 @@
             XPathFunctionResolver functionResolver,
             XPathVariableResolver variableResolver) {
         this(xpath, prefixResolver, functionResolver, variableResolver,
-             false, true, new JdkXmlFeatures(false));
+             false, new JdkXmlFeatures(false));
     };
 
     protected XPathExpressionImpl(com.sun.org.apache.xpath.internal.XPath xpath,
             JAXPPrefixResolver prefixResolver,XPathFunctionResolver functionResolver,
             XPathVariableResolver variableResolver, boolean featureSecureProcessing,
-            boolean useServiceMechanism, JdkXmlFeatures featureManager) {
+            JdkXmlFeatures featureManager) {
         this.xpath = xpath;
         this.prefixResolver = prefixResolver;
         this.functionResolver = functionResolver;
         this.variableResolver = variableResolver;
         this.featureSecureProcessing = featureSecureProcessing;
-        this.useServiceMechanism = useServiceMechanism;
+        this.overrideDefaultParser = featureManager.getFeature(
+                JdkXmlFeatures.XmlFeature.JDK_OVERRIDE_PARSER);
         this.featureManager = featureManager;
     };
 
--- a/src/java.xml/share/classes/com/sun/org/apache/xpath/internal/jaxp/XPathFactoryImpl.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.xml/share/classes/com/sun/org/apache/xpath/internal/jaxp/XPathFactoryImpl.java	Fri Jan 12 15:05:35 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2017, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * Licensed to the Apache Software Foundation (ASF) under one or more
@@ -60,29 +60,21 @@
          * <p>State of secure mode.</p>
          */
         private boolean _isSecureMode = false;
+
+        /**
+         * XML Features manager
+         */
+        private final JdkXmlFeatures _featureManager;
+
         /**
          * javax.xml.xpath.XPathFactory implementation.
          */
-
-        private boolean _useServicesMechanism = true;
-
-        private final JdkXmlFeatures _featureManager;
-
         public XPathFactoryImpl() {
-            this(true);
-        }
-
-        public static XPathFactory newXPathFactoryNoServiceLoader() {
-            return new XPathFactoryImpl(false);
-        }
-
-        public XPathFactoryImpl(boolean useServicesMechanism) {
             if (System.getSecurityManager() != null) {
                 _isSecureMode = true;
                 _isNotSecureProcessing = false;
             }
             _featureManager = new JdkXmlFeatures(!_isNotSecureProcessing);
-            this._useServicesMechanism = useServicesMechanism;
         }
         /**
          * <p>Is specified object model supported by this
@@ -132,8 +124,7 @@
         public javax.xml.xpath.XPath newXPath() {
             return new com.sun.org.apache.xpath.internal.jaxp.XPathImpl(
                     xPathVariableResolver, xPathFunctionResolver,
-                    !_isNotSecureProcessing, _useServicesMechanism,
-                    _featureManager );
+                    !_isNotSecureProcessing, _featureManager );
         }
 
         /**
@@ -192,10 +183,9 @@
                 return;
             }
             if (name.equals(XalanConstants.ORACLE_FEATURE_SERVICE_MECHANISM)) {
-                //in secure mode, let _useServicesMechanism be determined by the constructor
-                if (!_isSecureMode)
-                    _useServicesMechanism = value;
-                return;
+                // for compatibility, in secure mode, useServicesMechanism is determined by the constructor
+                if (_isSecureMode)
+                    return;
             }
 
             if (_featureManager != null &&
@@ -248,9 +238,6 @@
             if (name.equals(XMLConstants.FEATURE_SECURE_PROCESSING)) {
                 return !_isNotSecureProcessing;
             }
-            if (name.equals(XalanConstants.ORACLE_FEATURE_SERVICE_MECHANISM)) {
-                return _useServicesMechanism;
-            }
 
             /** Check to see if the property is managed by the feature manager **/
             int index = _featureManager.getIndex(name);
--- a/src/java.xml/share/classes/com/sun/org/apache/xpath/internal/jaxp/XPathImpl.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.xml/share/classes/com/sun/org/apache/xpath/internal/jaxp/XPathImpl.java	Fri Jan 12 15:05:35 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2017, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * Licensed to the Apache Software Foundation (ASF) under one or more
@@ -54,17 +54,18 @@
     private NamespaceContext namespaceContext=null;
 
     XPathImpl(XPathVariableResolver vr, XPathFunctionResolver fr) {
-        this(vr, fr, false, true, new JdkXmlFeatures(false));
+        this(vr, fr, false, new JdkXmlFeatures(false));
     }
 
     XPathImpl(XPathVariableResolver vr, XPathFunctionResolver fr,
-            boolean featureSecureProcessing, boolean useServiceMechanism,
-            JdkXmlFeatures featureManager) {
+            boolean featureSecureProcessing, JdkXmlFeatures featureManager) {
         this.origVariableResolver = this.variableResolver = vr;
         this.origFunctionResolver = this.functionResolver = fr;
         this.featureSecureProcessing = featureSecureProcessing;
-        this.useServiceMechanism = useServiceMechanism;
         this.featureManager = featureManager;
+        overrideDefaultParser = featureManager.getFeature(
+                JdkXmlFeatures.XmlFeature.JDK_OVERRIDE_PARSER);
+
     }
 
 
@@ -163,7 +164,7 @@
             // Can have errorListener
             XPathExpressionImpl ximpl = new XPathExpressionImpl (xpath,
                     prefixResolver, functionResolver, variableResolver,
-                    featureSecureProcessing, useServiceMechanism, featureManager);
+                    featureSecureProcessing, featureManager);
             return ximpl;
         } catch (TransformerException te) {
             throw new XPathExpressionException (te) ;
--- a/src/java.xml/share/classes/com/sun/org/apache/xpath/internal/jaxp/XPathImplUtil.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.xml/share/classes/com/sun/org/apache/xpath/internal/jaxp/XPathImplUtil.java	Fri Jan 12 15:05:35 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -26,7 +26,6 @@
 package com.sun.org.apache.xpath.internal.jaxp;
 
 import com.sun.org.apache.xalan.internal.res.XSLMessages;
-import com.sun.org.apache.xalan.internal.utils.FactoryImpl;
 import com.sun.org.apache.xml.internal.dtm.DTM;
 import com.sun.org.apache.xpath.internal.axes.LocPathIterator;
 import com.sun.org.apache.xpath.internal.objects.XObject;
@@ -43,6 +42,7 @@
 import javax.xml.xpath.XPathNodes;
 import javax.xml.xpath.XPathVariableResolver;
 import jdk.xml.internal.JdkXmlFeatures;
+import jdk.xml.internal.JdkXmlUtils;
 import org.w3c.dom.Document;
 import org.w3c.dom.Node;
 import org.w3c.dom.traversal.NodeIterator;
@@ -57,7 +57,7 @@
     XPathFunctionResolver functionResolver;
     XPathVariableResolver variableResolver;
     JAXPPrefixResolver prefixResolver;
-    boolean useServiceMechanism = true;
+    boolean overrideDefaultParser;
     // By default Extension Functions are allowed in XPath Expressions. If
     // Secure Processing Feature is set on XPathFactory then the invocation of
     // extensions function need to throw XPathFunctionException
@@ -125,9 +125,7 @@
             //
             // so we really have to create a fresh DocumentBuilder every time we need one
             // - KK
-            DocumentBuilderFactory dbf = FactoryImpl.getDOMFactory(useServiceMechanism);
-            dbf.setNamespaceAware(true);
-            dbf.setValidating(false);
+            DocumentBuilderFactory dbf = JdkXmlUtils.getDOMFactory(overrideDefaultParser);
             return dbf.newDocumentBuilder().parse(source);
         } catch (ParserConfigurationException | SAXException | IOException e) {
             throw new XPathExpressionException (e);
--- a/src/java.xml/share/classes/javax/xml/transform/FactoryFinder.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.xml/share/classes/javax/xml/transform/FactoryFinder.java	Fri Jan 12 15:05:35 2018 -0800
@@ -143,10 +143,11 @@
      * @param doFallback True if the current ClassLoader should be tried as
      * a fallback if the class is not found using cl
      *
-     * @param useServicesMechanism True use services mechanism
+     * @param overrideDefaultParser True to allow overriding the system-default
+     * parser.
      */
     static <T> T newInstance(Class<T> type, String className, ClassLoader cl,
-                             boolean doFallback, boolean useServicesMechanism)
+                             boolean doFallback)
         throws TransformerFactoryConfigurationError
     {
         assert type != null;
@@ -165,13 +166,8 @@
             if (!type.isAssignableFrom(providerClass)) {
                 throw new ClassCastException(className + " cannot be cast to " + type.getName());
             }
-            Object instance = null;
-            if (!useServicesMechanism) {
-                instance = newInstanceNoServiceLoader(type, providerClass);
-            }
-            if (instance == null) {
-                instance = providerClass.getConstructor().newInstance();
-            }
+            Object instance = providerClass.getConstructor().newInstance();
+
             final ClassLoader clD = cl;
             dPrint(()->"created new instance of " + providerClass +
                        " using ClassLoader: " + clD);
@@ -188,48 +184,6 @@
     }
 
     /**
-     * Try to construct using newTransformerFactoryNoServiceLoader
-     *   method if available.
-     */
-    private static <T> T newInstanceNoServiceLoader(Class<T> type, Class<?> providerClass) {
-        // Retain maximum compatibility if no security manager.
-        if (System.getSecurityManager() == null) {
-            return null;
-        }
-        try {
-            final Method creationMethod =
-                    providerClass.getDeclaredMethod(
-                        "newTransformerFactoryNoServiceLoader"
-                    );
-            final int modifiers = creationMethod.getModifiers();
-
-            // Do not call the method if it's not public static.
-            if (!Modifier.isPublic(modifiers) || !Modifier.isStatic(modifiers)) {
-                return null;
-            }
-
-            // Only call the method if it's declared to return an instance of
-            // TransformerFactory
-            final Class<?> returnType = creationMethod.getReturnType();
-            if (type.isAssignableFrom(returnType)) {
-                final Object result = creationMethod.invoke(null, (Object[])null);
-                return type.cast(result);
-            } else {
-                // This should not happen, as
-                // TransformerFactoryImpl.newTransformerFactoryNoServiceLoader is
-                // declared to return TransformerFactory.
-                throw new ClassCastException(returnType + " cannot be cast to " + type);
-            }
-        } catch (ClassCastException e) {
-            throw new TransformerFactoryConfigurationError(e, e.getMessage());
-        } catch (NoSuchMethodException exc) {
-            return null;
-        } catch (Exception exc) {
-            return null;
-        }
-    }
-
-    /**
      * Finds the implementation Class object in the specified order.  Main
      * entry point.
      * @return Class object of factory, never null
@@ -255,7 +209,7 @@
             String systemProp = SecuritySupport.getSystemProperty(factoryId);
             if (systemProp != null) {
                 dPrint(()->"found system property, value=" + systemProp);
-                return newInstance(type, systemProp, null, true, true);
+                return newInstance(type, systemProp, null, true);
             }
         }
         catch (SecurityException se) {
@@ -282,7 +236,7 @@
 
             if (factoryClassName != null) {
                 dPrint(()->"found in ${java.home}/conf/jaxp.properties, value=" + factoryClassName);
-                return newInstance(type, factoryClassName, null, true, true);
+                return newInstance(type, factoryClassName, null, true);
             }
         }
         catch (Exception ex) {
@@ -300,7 +254,7 @@
         }
 
         dPrint(()->"loaded from fallback value: " + fallbackClassName);
-        return newInstance(type, fallbackClassName, null, true, true);
+        return newInstance(type, fallbackClassName, null, true);
     }
 
     /*
--- a/src/java.xml/share/classes/javax/xml/transform/TransformerFactory.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.xml/share/classes/javax/xml/transform/TransformerFactory.java	Fri Jan 12 15:05:35 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -62,7 +62,7 @@
      * @since 9
      */
     public static TransformerFactory newDefaultInstance() {
-        return TransformerFactoryImpl.newTransformerFactoryNoServiceLoader();
+        return new TransformerFactoryImpl();
     }
 
     /**
@@ -170,7 +170,7 @@
 
         //do not fallback if given classloader can't find the class, throw exception
         return  FactoryFinder.newInstance(TransformerFactory.class,
-                    factoryClassName, classLoader, false, false);
+                    factoryClassName, classLoader, false);
     }
     /**
      * Process the {@code Source} into a {@code Transformer}
--- a/src/java.xml/share/classes/javax/xml/validation/SchemaFactory.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.xml/share/classes/javax/xml/validation/SchemaFactory.java	Fri Jan 12 15:05:35 2018 -0800
@@ -139,7 +139,7 @@
      * @since 9
      */
     public static SchemaFactory newDefaultInstance() {
-        return XMLSchemaFactory.newXMLSchemaFactoryNoServiceLoader();
+        return new XMLSchemaFactory();
     }
 
     /**
--- a/src/java.xml/share/classes/javax/xml/validation/SchemaFactoryFinder.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.xml/share/classes/javax/xml/validation/SchemaFactoryFinder.java	Fri Jan 12 15:05:35 2018 -0800
@@ -25,6 +25,7 @@
 
 package javax.xml.validation;
 
+import com.sun.org.apache.xerces.internal.jaxp.validation.XMLSchemaFactory;
 import java.io.File;
 import java.lang.reflect.InvocationTargetException;
 import java.lang.reflect.Method;
@@ -167,7 +168,7 @@
             String r = SecuritySupport.getSystemProperty(propertyName);
             if(r!=null) {
                 debugPrintln(()->"The value is '"+r+"'");
-                sf = createInstance(r, true);
+                sf = createInstance(r);
                 if(sf!=null)    return sf;
             } else
                 debugPrintln(()->"The property is undefined.");
@@ -201,7 +202,7 @@
             debugPrintln(()->"found " + factoryClassName + " in $java.home/conf/jaxp.properties");
 
             if (factoryClassName != null) {
-                sf = createInstance(factoryClassName, true);
+                sf = createInstance(factoryClassName);
                 if(sf != null){
                     return sf;
                 }
@@ -226,7 +227,7 @@
         // platform default
         if(schemaLanguage.equals("http://www.w3.org/2001/XMLSchema")) {
             debugPrintln(()->"attempting to use the platform default XML Schema validator");
-            return createInstance("com.sun.org.apache.xerces.internal.jaxp.validation.XMLSchemaFactory", true);
+            return new XMLSchemaFactory();
         }
 
         debugPrintln(()->"all things were tried, but none was found. bailing out.");
@@ -273,11 +274,7 @@
      * @return null
      *      if it fails. Error messages will be printed by this method.
      */
-    SchemaFactory createInstance( String className ) {
-        return createInstance( className, false );
-    }
-
-    SchemaFactory createInstance( String className, boolean useServicesMechanism ) {
+    SchemaFactory createInstance(String className) {
         SchemaFactory schemaFactory = null;
 
         debugPrintln(()->"createInstance(" + className + ")");
@@ -296,12 +293,7 @@
                 throw new ClassCastException(clazz.getName()
                             + " cannot be cast to " + SchemaFactory.class);
             }
-            if (!useServicesMechanism) {
-                schemaFactory = newInstanceNoServiceLoader(clazz);
-            }
-            if (schemaFactory == null) {
-                schemaFactory = (SchemaFactory) clazz.getConstructor().newInstance();
-            }
+            schemaFactory = (SchemaFactory) clazz.getConstructor().newInstance();
         } catch (ClassCastException | IllegalAccessException | IllegalArgumentException |
             InstantiationException | InvocationTargetException | NoSuchMethodException |
             SecurityException ex) {
@@ -315,50 +307,6 @@
         return schemaFactory;
     }
 
-    /**
-     * Try to construct using newXMLSchemaFactoryNoServiceLoader
-     *   method if available.
-     */
-    private static SchemaFactory newInstanceNoServiceLoader(
-         Class<?> providerClass
-    ) {
-        // Retain maximum compatibility if no security manager.
-        if (System.getSecurityManager() == null) {
-            return null;
-        }
-        try {
-            final Method creationMethod =
-                providerClass.getDeclaredMethod(
-                    "newXMLSchemaFactoryNoServiceLoader"
-                );
-            final int modifiers = creationMethod.getModifiers();
-
-            // Do not call the method if it's not public static.
-            if (!Modifier.isStatic(modifiers) || !Modifier.isPublic(modifiers)) {
-                return null;
-            }
-
-            // Only calls "newXMLSchemaFactoryNoServiceLoader" if it's
-            // declared to return an instance of SchemaFactory.
-            final Class<?> returnType = creationMethod.getReturnType();
-            if (SERVICE_CLASS.isAssignableFrom(returnType)) {
-                return SERVICE_CLASS.cast(creationMethod.invoke(null, (Object[])null));
-            } else {
-                // Should not happen since
-                // XMLSchemaFactory.newXMLSchemaFactoryNoServiceLoader is
-                // declared to return XMLSchemaFactory.
-                throw new ClassCastException(returnType
-                            + " cannot be cast to " + SERVICE_CLASS);
-            }
-        } catch(ClassCastException e) {
-            throw new SchemaFactoryConfigurationError(e.getMessage(), e);
-        } catch (NoSuchMethodException exc) {
-            return null;
-        } catch (Exception exc) {
-            return null;
-        }
-    }
-
     // Call isSchemaLanguageSupported with initial context.
     private boolean isSchemaLanguageSupportedBy(final SchemaFactory factory,
             final String schemaLanguage,
--- a/src/java.xml/share/classes/javax/xml/xpath/XPathFactory.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.xml/share/classes/javax/xml/xpath/XPathFactory.java	Fri Jan 12 15:05:35 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -87,7 +87,7 @@
      * @since 9
      */
     public static XPathFactory newDefaultInstance() {
-        return XPathFactoryImpl.newXPathFactoryNoServiceLoader();
+        return new XPathFactoryImpl();
     }
 
     /**
--- a/src/java.xml/share/classes/javax/xml/xpath/XPathFactoryFinder.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.xml/share/classes/javax/xml/xpath/XPathFactoryFinder.java	Fri Jan 12 15:05:35 2018 -0800
@@ -25,10 +25,9 @@
 
 package javax.xml.xpath;
 
+import com.sun.org.apache.xpath.internal.jaxp.XPathFactoryImpl;
 import java.io.File;
 import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.lang.reflect.Modifier;
 import java.security.AccessControlContext;
 import java.security.AccessController;
 import java.security.PrivilegedAction;
@@ -162,7 +161,7 @@
             String r = SecuritySupport.getSystemProperty(propertyName);
             if(r!=null) {
                 debugPrintln(()->"The value is '"+r+"'");
-                xpathFactory = createInstance(r, true);
+                xpathFactory = createInstance(r);
                 if (xpathFactory != null) {
                     return xpathFactory;
                 }
@@ -197,7 +196,7 @@
             debugPrintln(()->"found " + factoryClassName + " in $java.home/conf/jaxp.properties");
 
             if (factoryClassName != null) {
-                xpathFactory = createInstance(factoryClassName, true);
+                xpathFactory = createInstance(factoryClassName);
                 if(xpathFactory != null){
                     return xpathFactory;
                 }
@@ -223,7 +222,7 @@
         // platform default
         if(uri.equals(XPathFactory.DEFAULT_OBJECT_MODEL_URI)) {
             debugPrintln(()->"attempting to use the platform default W3C DOM XPath lib");
-            return createInstance("com.sun.org.apache.xpath.internal.jaxp.XPathFactoryImpl", true);
+            return new XPathFactoryImpl();
         }
 
         debugPrintln(()->"all things were tried, but none was found. bailing out.");
@@ -271,13 +270,7 @@
      * @return null
      *      if it fails. Error messages will be printed by this method.
      */
-    XPathFactory createInstance( String className )
-            throws XPathFactoryConfigurationException
-    {
-        return createInstance( className, false );
-    }
-
-    XPathFactory createInstance( String className, boolean useServicesMechanism  )
+    XPathFactory createInstance(String className)
             throws XPathFactoryConfigurationException
     {
         XPathFactory xPathFactory = null;
@@ -294,12 +287,7 @@
 
         // instantiate Class as a XPathFactory
         try {
-            if (!useServicesMechanism) {
-                xPathFactory = newInstanceNoServiceLoader(clazz);
-            }
-            if (xPathFactory == null) {
-                xPathFactory = (XPathFactory) clazz.getConstructor().newInstance();
-            }
+            xPathFactory = (XPathFactory) clazz.getConstructor().newInstance();
         } catch (ClassCastException | IllegalAccessException | IllegalArgumentException |
             InstantiationException | InvocationTargetException | NoSuchMethodException |
             SecurityException ex) {
@@ -312,50 +300,6 @@
 
         return xPathFactory;
     }
-    /**
-     * Try to construct using newXPathFactoryNoServiceLoader
-     *   method if available.
-     */
-    private static XPathFactory newInstanceNoServiceLoader(
-         Class<?> providerClass
-    ) throws XPathFactoryConfigurationException {
-        // Retain maximum compatibility if no security manager.
-        if (System.getSecurityManager() == null) {
-            return null;
-        }
-        try {
-            Method creationMethod =
-                    providerClass.getDeclaredMethod(
-                        "newXPathFactoryNoServiceLoader"
-                    );
-            final int modifiers = creationMethod.getModifiers();
-
-            // Do not call "newXPathFactoryNoServiceLoader" if it's
-            // not public static.
-            if (!Modifier.isStatic(modifiers) || !Modifier.isPublic(modifiers)) {
-                return null;
-            }
-
-            // Only calls "newXPathFactoryNoServiceLoader" if it's
-            // declared to return an instance of XPathFactory.
-            final Class<?> returnType = creationMethod.getReturnType();
-            if (SERVICE_CLASS.isAssignableFrom(returnType)) {
-                return SERVICE_CLASS.cast(creationMethod.invoke(null, (Object[])null));
-            } else {
-                // Should not happen since
-                // XPathFactoryImpl.newXPathFactoryNoServiceLoader is
-                // declared to return XPathFactory.
-                throw new ClassCastException(returnType
-                            + " cannot be cast to " + SERVICE_CLASS);
-            }
-        } catch (ClassCastException e) {
-            throw new XPathFactoryConfigurationException(e);
-        } catch (NoSuchMethodException exc) {
-            return null;
-        } catch (Exception exc) {
-            return null;
-        }
-    }
 
     // Call isObjectModelSupportedBy with initial context.
     private boolean isObjectModelSupportedBy(final XPathFactory factory,
--- a/src/java.xml/share/classes/jdk/xml/internal/JdkXmlFeatures.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.xml/share/classes/jdk/xml/internal/JdkXmlFeatures.java	Fri Jan 12 15:05:35 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -26,6 +26,7 @@
 package jdk.xml.internal;
 
 import javax.xml.XMLConstants;
+import static jdk.xml.internal.JdkXmlUtils.OVERRIDE_PARSER;
 import static jdk.xml.internal.JdkXmlUtils.SP_USE_CATALOG;
 import static jdk.xml.internal.JdkXmlUtils.RESET_SYMBOL_TABLE;
 
@@ -36,6 +37,13 @@
 public class JdkXmlFeatures {
     public static final String ORACLE_JAXP_PROPERTY_PREFIX =
         "http://www.oracle.com/xml/jaxp/properties/";
+
+    public static final String XML_FEATURE_MANAGER =
+            ORACLE_JAXP_PROPERTY_PREFIX + "XmlFeatureManager";
+
+    public static final String ORACLE_FEATURE_SERVICE_MECHANISM =
+            "http://www.oracle.com/feature/use-service-mechanism";
+
     /**
      * Feature enableExtensionFunctions
      */
@@ -56,22 +64,37 @@
          * FSP: extension function is enforced by FSP. When FSP is on, extension
          * function is disabled.
          */
-        ENABLE_EXTENSION_FUNCTION(ORACLE_ENABLE_EXTENSION_FUNCTION,
-                SP_ENABLE_EXTENSION_FUNCTION_SPEC, true, false, true, true),
+        ENABLE_EXTENSION_FUNCTION(ORACLE_ENABLE_EXTENSION_FUNCTION, SP_ENABLE_EXTENSION_FUNCTION_SPEC,
+                ORACLE_ENABLE_EXTENSION_FUNCTION, SP_ENABLE_EXTENSION_FUNCTION,
+                true, false, true, true),
         /**
          * The {@link javax.xml.XMLConstants.USE_CATALOG} feature.
          * FSP: USE_CATALOG is not enforced by FSP.
          */
-        USE_CATALOG(PROPERTY_USE_CATALOG, SP_USE_CATALOG, true, false, true, false),
+        USE_CATALOG(PROPERTY_USE_CATALOG, SP_USE_CATALOG,
+                null, null,
+                true, false, true, false),
 
         /**
          * Feature resetSymbolTable
          * FSP: RESET_SYMBOL_TABLE_FEATURE is not enforced by FSP.
          */
-        RESET_SYMBOL_TABLE_FEATURE(RESET_SYMBOL_TABLE, RESET_SYMBOL_TABLE, false, false, true, false);
+        RESET_SYMBOL_TABLE_FEATURE(RESET_SYMBOL_TABLE, RESET_SYMBOL_TABLE,
+                null, null,
+                false, false, true, false),
+
+        /**
+         * Feature overrideDefaultParser
+         * FSP: not enforced by FSP.
+         */
+        JDK_OVERRIDE_PARSER(OVERRIDE_PARSER, OVERRIDE_PARSER,
+                ORACLE_FEATURE_SERVICE_MECHANISM, ORACLE_FEATURE_SERVICE_MECHANISM,
+                false, false, true, false);
 
         private final String name;
         private final String nameSP;
+        private final String nameOld;
+        private final String nameOldSP;
         private final boolean valueDefault;
         private final boolean valueEnforced;
         private final boolean hasSystem;
@@ -81,15 +104,20 @@
          * Constructs an XmlFeature instance.
          * @param name the name of the feature
          * @param nameSP the name of the System Property
+         * @param nameOld the name of the corresponding legacy property
+         * @param nameOldSP the system property of the legacy property
          * @param value the value of the feature
          * @param hasSystem a flag to indicate whether the feature is supported
          * @param enforced a flag indicating whether the feature is
          * FSP (Feature_Secure_Processing) enforced
          * with a System property
          */
-        XmlFeature(String name, String nameSP, boolean value, boolean valueEnforced, boolean hasSystem, boolean enforced) {
+        XmlFeature(String name, String nameSP, String nameOld, String nameOldSP,
+                boolean value, boolean valueEnforced, boolean hasSystem, boolean enforced) {
             this.name = name;
             this.nameSP = nameSP;
+            this.nameOld = nameOld;
+            this.nameOldSP = nameOldSP;
             this.valueDefault = value;
             this.valueEnforced = valueEnforced;
             this.hasSystem = hasSystem;
@@ -103,7 +131,8 @@
          * otherwise
          */
         boolean equalsPropertyName(String propertyName) {
-            return name.equals(propertyName);
+            return name.equals(propertyName) ||
+                    (nameOld != null && nameOld.equals(propertyName));
         }
 
         /**
@@ -125,6 +154,15 @@
         }
 
         /**
+         * Returns the name of the legacy System Property.
+         *
+         * @return the name of the legacy System Property
+         */
+        String systemPropertyOld() {
+            return nameOldSP;
+        }
+
+        /**
          * Returns the default value of the property.
          * @return the default value of the property
          */
@@ -159,30 +197,6 @@
     }
 
     /**
-     * Maps old property names with the new ones. This map is used to keep track of
-     * name changes so that old or incorrect names continue to be supported for compatibility.
-     */
-    public static enum NameMap {
-
-        ENABLE_EXTENSION_FUNCTION(SP_ENABLE_EXTENSION_FUNCTION_SPEC, SP_ENABLE_EXTENSION_FUNCTION);
-
-        final String newName;
-        final String oldName;
-
-        NameMap(String newName, String oldName) {
-            this.newName = newName;
-            this.oldName = oldName;
-        }
-
-        String getOldName(String newName) {
-            if (newName.equals(this.newName)) {
-                return oldName;
-            }
-            return null;
-        }
-    }
-
-    /**
      * States of the settings of a property, in the order: default value, value
      * set by FEATURE_SECURE_PROCESSING, jaxp.properties file, jaxp system
      * properties, and jaxp api properties
@@ -207,12 +221,12 @@
     /**
      * Values of the features
      */
-    private boolean[] featureValues;
+    private final boolean[] featureValues;
 
     /**
      * States of the settings for each property
      */
-    private State[] states;
+    private final State[] states;
 
     /**
      * Flag indicating if secure processing is set
@@ -349,14 +363,11 @@
      */
     private void readSystemProperties() {
         for (XmlFeature feature : XmlFeature.values()) {
-            getSystemProperty(feature, feature.systemProperty());
             if (!getSystemProperty(feature, feature.systemProperty())) {
                 //if system property is not found, try the older form if any
-                for (NameMap nameMap : NameMap.values()) {
-                    String oldName = nameMap.getOldName(feature.systemProperty());
-                    if (oldName != null) {
-                        getSystemProperty(feature, oldName);
-                    }
+                String oldName = feature.systemPropertyOld();
+                if (oldName != null) {
+                    getSystemProperty(feature, oldName);
                 }
             }
         }
@@ -367,6 +378,7 @@
      *
      * @param property the type of the property
      * @param sysPropertyName the name of system property
+     * @return true if the system property is found, false otherwise
      */
     private boolean getSystemProperty(XmlFeature feature, String sysPropertyName) {
         try {
--- a/src/java.xml/share/classes/jdk/xml/internal/JdkXmlUtils.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/java.xml/share/classes/jdk/xml/internal/JdkXmlUtils.java	Fri Jan 12 15:05:35 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -22,16 +22,26 @@
  * or visit www.oracle.com if you need additional information or have any
  * questions.
  */
-
 package jdk.xml.internal;
 
 import com.sun.org.apache.xalan.internal.utils.XMLSecurityManager;
+import com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl;
+import com.sun.org.apache.xerces.internal.impl.Constants;
+import com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl;
+import com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl;
 import com.sun.org.apache.xerces.internal.util.ParserConfigurationSettings;
 import com.sun.org.apache.xerces.internal.xni.parser.XMLComponentManager;
 import com.sun.org.apache.xerces.internal.xni.parser.XMLConfigurationException;
 import javax.xml.XMLConstants;
 import javax.xml.catalog.CatalogFeatures;
 import javax.xml.catalog.CatalogFeatures.Feature;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.parsers.SAXParserFactory;
+import javax.xml.transform.TransformerConfigurationException;
+import javax.xml.transform.sax.SAXTransformerFactory;
+import org.w3c.dom.Document;
+import org.xml.sax.SAXException;
 import org.xml.sax.SAXNotRecognizedException;
 import org.xml.sax.SAXNotSupportedException;
 import org.xml.sax.XMLReader;
@@ -40,6 +50,18 @@
  * Constants for use across JAXP processors.
  */
 public class JdkXmlUtils {
+    private static final String DOM_FACTORY_ID = "javax.xml.parsers.DocumentBuilderFactory";
+    private static final String SAX_FACTORY_ID = "javax.xml.parsers.SAXParserFactory";
+    private static final String SAX_DRIVER = "org.xml.sax.driver";
+
+    /**
+     * Xerces features
+     */
+    public static final String NAMESPACES_FEATURE =
+        Constants.SAX_FEATURE_PREFIX + Constants.NAMESPACES_FEATURE;
+    public static final String NAMESPACE_PREFIXES_FEATURE =
+        Constants.SAX_FEATURE_PREFIX + Constants.NAMESPACE_PREFIXES_FEATURE;
+
 
     /**
      * Catalog features
@@ -52,12 +74,20 @@
     public final static String CATALOG_RESOLVE = CatalogFeatures.Feature.RESOLVE.getPropertyName();
 
     /**
-     * Reset SymbolTable feature
-     * System property name is identical to feature name
+     * Reset SymbolTable feature System property name is identical to feature
+     * name
      */
     public final static String RESET_SYMBOL_TABLE = "jdk.xml.resetSymbolTable";
 
     /**
+     * jdk.xml.overrideDefaultParser: enables the use of a 3rd party's parser
+     * implementation to override the system-default parser.
+     */
+    public static final String OVERRIDE_PARSER = "jdk.xml.overrideDefaultParser";
+    public static final boolean OVERRIDE_PARSER_DEFAULT = SecuritySupport.getJAXPSystemProperty(
+                    Boolean.class, OVERRIDE_PARSER, "false");
+
+    /**
      * Values for a feature
      */
     public static final String FEATURE_TRUE = "true";
@@ -75,7 +105,6 @@
     public static final boolean RESET_SYMBOL_TABLE_DEFAULT
             = SecuritySupport.getJAXPSystemProperty(Boolean.class, RESET_SYMBOL_TABLE, "false");
 
-
     /**
      * JDK features (will be consolidated in the next major feature revamp
      */
@@ -84,6 +113,11 @@
             = SecuritySupport.getJAXPSystemProperty(Integer.class, CDATA_CHUNK_SIZE, "0");
 
     /**
+     * The system-default factory
+     */
+    private static final SAXParserFactory defaultSAXFactory = getSAXFactory(false);
+
+    /**
      * Returns the value.
      *
      * @param value the specified value
@@ -227,4 +261,153 @@
             }
         }
     }
+
+    /**
+     * Returns an XMLReader instance. If overrideDefaultParser is requested, use
+     * SAXParserFactory or XMLReaderFactory, otherwise use the system-default
+     * SAXParserFactory to locate an XMLReader.
+     *
+     * @param overrideDefaultParser a flag indicating whether a 3rd party's
+     * parser implementation may be used to override the system-default one
+     * @param secureProcessing a flag indicating whether secure processing is
+     * requested
+     * @param useXMLReaderFactory a flag indicating when the XMLReader should be
+     * created using XMLReaderFactory. True is a compatibility mode that honors
+     * the property org.xml.sax.driver (see JDK-6490921).
+     * @return an XMLReader instance
+     */
+    public static XMLReader getXMLReader(boolean overrideDefaultParser,
+            boolean secureProcessing) {
+        SAXParserFactory saxFactory;
+        XMLReader reader = null;
+        String spSAXDriver = SecuritySupport.getSystemProperty(SAX_DRIVER);
+        if (spSAXDriver != null) {
+            reader = getXMLReaderWXMLReaderFactory();
+        } else if (overrideDefaultParser) {
+            reader = getXMLReaderWSAXFactory(overrideDefaultParser);
+        }
+
+        if (reader != null) {
+            if (secureProcessing) {
+                try {
+                    reader.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, secureProcessing);
+                } catch (SAXException e) {
+                    XMLSecurityManager.printWarning(reader.getClass().getName(),
+                            XMLConstants.FEATURE_SECURE_PROCESSING, e);
+                }
+            }
+            try {
+                reader.setFeature(NAMESPACES_FEATURE, true);
+                reader.setFeature(NAMESPACE_PREFIXES_FEATURE, false);
+            } catch (SAXException se) {
+                // older version of a parser
+            }
+            return reader;
+        }
+
+        // use the system-default
+        saxFactory = defaultSAXFactory;
+
+        try {
+            reader = saxFactory.newSAXParser().getXMLReader();
+        } catch (ParserConfigurationException | SAXException ex) {
+            // shall not happen with the system-default reader
+        }
+        return reader;
+    }
+
+    /**
+     * Creates a system-default DOM Document.
+     *
+     * @return a DOM Document instance
+     */
+    public static Document getDOMDocument() {
+        try {
+            DocumentBuilderFactory dbf = JdkXmlUtils.getDOMFactory(false);
+            return dbf.newDocumentBuilder().newDocument();
+        } catch (ParserConfigurationException pce) {
+            // can never happen with the system-default configuration
+        }
+        return null;
+    }
+
+    /**
+     * Returns a DocumentBuilderFactory instance.
+     *
+     * @param overrideDefaultParser a flag indicating whether the system-default
+     * implementation may be overridden. If the system property of the
+     * DOM factory ID is set, override is always allowed.
+     *
+     * @return a DocumentBuilderFactory instance.
+     */
+    public static DocumentBuilderFactory getDOMFactory(boolean overrideDefaultParser) {
+        boolean override = overrideDefaultParser;
+        String spDOMFactory = SecuritySupport.getJAXPSystemProperty(DOM_FACTORY_ID);
+
+        if (spDOMFactory != null && System.getSecurityManager() == null) {
+            override = true;
+        }
+        DocumentBuilderFactory dbf
+                = !override
+                        ? new DocumentBuilderFactoryImpl()
+                        : DocumentBuilderFactory.newInstance();
+        dbf.setNamespaceAware(true);
+        // false is the default setting. This step here is for compatibility
+        dbf.setValidating(false);
+        return dbf;
+    }
+
+    /**
+     * Returns a SAXParserFactory instance.
+     *
+     * @param overrideDefaultParser a flag indicating whether the system-default
+     * implementation may be overridden. If the system property of the
+     * DOM factory ID is set, override is always allowed.
+     *
+     * @return a SAXParserFactory instance.
+     */
+    public static SAXParserFactory getSAXFactory(boolean overrideDefaultParser) {
+        boolean override = overrideDefaultParser;
+        String spSAXFactory = SecuritySupport.getJAXPSystemProperty(SAX_FACTORY_ID);
+        if (spSAXFactory != null && System.getSecurityManager() == null) {
+            override = true;
+        }
+
+        SAXParserFactory factory
+                = !override
+                        ? new SAXParserFactoryImpl()
+                        : SAXParserFactory.newInstance();
+        factory.setNamespaceAware(true);
+        return factory;
+    }
+
+    public static SAXTransformerFactory getSAXTransformFactory(boolean overrideDefaultParser) {
+        SAXTransformerFactory tf = overrideDefaultParser
+                ? (SAXTransformerFactory) SAXTransformerFactory.newInstance()
+                : (SAXTransformerFactory) new TransformerFactoryImpl();
+        try {
+            tf.setFeature(OVERRIDE_PARSER, overrideDefaultParser);
+        } catch (TransformerConfigurationException ex) {
+            // ignore since it'd never happen with the JDK impl.
+        }
+        return tf;
+    }
+
+    private static XMLReader getXMLReaderWSAXFactory(boolean overrideDefaultParser) {
+        SAXParserFactory saxFactory = getSAXFactory(overrideDefaultParser);
+        try {
+            return saxFactory.newSAXParser().getXMLReader();
+        } catch (ParserConfigurationException | SAXException ex) {
+            return getXMLReaderWXMLReaderFactory();
+        }
+    }
+
+    @SuppressWarnings("deprecation")
+    private static XMLReader getXMLReaderWXMLReaderFactory() {
+        try {
+            return org.xml.sax.helpers.XMLReaderFactory.createXMLReader();
+        } catch (SAXException ex1) {
+        }
+        return null;
+    }
 }
--- a/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11KeyAgreement.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11KeyAgreement.java	Fri Jan 12 15:05:35 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -69,6 +69,17 @@
     // KeyAgreement from SunJCE as fallback for > 2 party agreement
     private KeyAgreement multiPartyAgreement;
 
+    private static class AllowKDF {
+
+        private static final boolean VALUE = getValue();
+
+        private static boolean getValue() {
+            return AccessController.doPrivileged(
+                (PrivilegedAction<Boolean>)
+                () -> Boolean.getBoolean("jdk.crypto.KeyAgreement.legacyKDF"));
+        }
+    }
+
     P11KeyAgreement(Token token, String algorithm, long mechanism) {
         super();
         this.token = token;
@@ -260,6 +271,7 @@
         if (algorithm == null) {
             throw new NoSuchAlgorithmException("Algorithm must not be null");
         }
+
         if (algorithm.equals("TlsPremasterSecret")) {
             // For now, only perform native derivation for TlsPremasterSecret
             // as that is required for FIPS compliance.
@@ -268,6 +280,14 @@
             // (bug not yet filed).
             return nativeGenerateSecret(algorithm);
         }
+
+        if (!algorithm.equalsIgnoreCase("TlsPremasterSecret") &&
+            !AllowKDF.VALUE) {
+
+            throw new NoSuchAlgorithmException("Unsupported secret key "
+                                               + "algorithm: " + algorithm);
+        }
+
         byte[] secret = engineGenerateSecret();
         // Maintain compatibility for SunJCE:
         // verify secret length is sensible for algorithm / truncate
--- a/src/jdk.hotspot.agent/share/classes/sun/jvm/hotspot/oops/CompiledICHolder.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/jdk.hotspot.agent/share/classes/sun/jvm/hotspot/oops/CompiledICHolder.java	Fri Jan 12 15:05:35 2018 -0800
@@ -40,10 +40,10 @@
   }
 
   private static synchronized void initialize(TypeDataBase db) throws WrongTypeException {
-    Type type    = db.lookupType("CompiledICHolder");
-    holderMethod = new MetadataField(type.getAddressField("_holder_method"), 0);
-    holderKlass  = new MetadataField(type.getAddressField("_holder_klass"), 0);
-    headerSize   = type.getSize();
+    Type type      = db.lookupType("CompiledICHolder");
+    holderMetadata = new MetadataField(type.getAddressField("_holder_metadata"), 0);
+    holderKlass    = new MetadataField(type.getAddressField("_holder_klass"), 0);
+    headerSize     = type.getSize();
   }
 
   public CompiledICHolder(Address addr) {
@@ -55,12 +55,12 @@
   private static long headerSize;
 
   // Fields
-  private static MetadataField holderMethod;
+  private static MetadataField holderMetadata;
   private static MetadataField holderKlass;
 
   // Accessors for declared fields
-  public Method getHolderMethod() { return (Method) holderMethod.getValue(this); }
-  public Klass  getHolderKlass()  { return (Klass)  holderKlass.getValue(this); }
+  public Metadata getHolderMetadata() { return (Metadata) holderMetadata.getValue(this); }
+  public Klass    getHolderKlass()    { return (Klass)    holderKlass.getValue(this); }
 
   public void printValueOn(PrintStream tty) {
     tty.print("CompiledICHolder");
--- a/src/jdk.management.agent/share/classes/sun/management/jmxremote/SingleEntryRegistry.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/jdk.management.agent/share/classes/sun/management/jmxremote/SingleEntryRegistry.java	Fri Jan 12 15:05:35 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -46,7 +46,7 @@
 public class SingleEntryRegistry extends RegistryImpl {
     SingleEntryRegistry(int port, String name, Remote object)
             throws RemoteException {
-        super(port);
+        super(port, null, null, SingleEntryRegistry::singleRegistryFilter);
         this.name = name;
         this.object = object;
     }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/jdk.naming.dns/share/classes/com/sun/jndi/dns/DNSDatagramSocketFactory.java	Fri Jan 12 15:05:35 2018 -0800
@@ -0,0 +1,246 @@
+/*
+ * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package com.sun.jndi.dns;
+
+import java.io.IOException;
+import java.net.DatagramSocket;
+import java.net.ProtocolFamily;
+import java.net.SocketException;
+import java.net.InetSocketAddress;
+import java.nio.channels.DatagramChannel;
+import java.util.Objects;
+import java.util.Random;
+
+class DNSDatagramSocketFactory {
+    static final int DEVIATION = 3;
+    static final int THRESHOLD = 6;
+    static final int BIT_DEVIATION = 2;
+    static final int HISTORY = 32;
+    static final int MAX_RANDOM_TRIES = 5;
+    /**
+     * The dynamic allocation port range (aka ephemeral ports), as configured
+     * on the system. Use nested class for lazy evaluation.
+     */
+    static final class EphemeralPortRange {
+        private EphemeralPortRange() {}
+        static final int LOWER = sun.net.PortConfig.getLower();
+        static final int UPPER = sun.net.PortConfig.getUpper();
+        static final int RANGE = UPPER - LOWER + 1;
+    }
+
+    // Records a subset of max {@code capacity} previously used ports
+    static final class PortHistory {
+        final int capacity;
+        final int[] ports;
+        final Random random;
+        int index;
+        PortHistory(int capacity, Random random) {
+            this.random = random;
+            this.capacity = capacity;
+            this.ports = new int[capacity];
+        }
+        // returns true if the history contains the specified port.
+        public boolean contains(int port) {
+            int p = 0;
+            for (int i=0; i<capacity; i++) {
+                if ((p = ports[i]) == 0 || p == port) break;
+            }
+            return p == port;
+        }
+        // Adds the port to the history - doesn't check whether the port
+        // is already present. Always adds the port and always return true.
+        public boolean add(int port) {
+            if (ports[index] != 0) { // at max capacity
+                // remove one port at random and store the new port there
+                ports[random.nextInt(capacity)] = port;
+            } else { // there's a free slot
+                ports[index] = port;
+            }
+            if (++index == capacity) index = 0;
+            return true;
+        }
+        // Adds the port to the history if not already present.
+        // Return true if the port was added, false if the port was already
+        // present.
+        public boolean offer(int port) {
+            if (contains(port)) return false;
+            else return add(port);
+        }
+    }
+
+    int lastport = 0;
+    int suitablePortCount;
+    int unsuitablePortCount;
+    final ProtocolFamily family; // null (default) means dual stack
+    final int thresholdCount; // decision point
+    final int deviation;
+    final Random random;
+    final PortHistory history;
+
+    DNSDatagramSocketFactory() {
+        this(new Random());
+    }
+
+    DNSDatagramSocketFactory(Random random) {
+        this(Objects.requireNonNull(random), null, DEVIATION, THRESHOLD);
+    }
+    DNSDatagramSocketFactory(Random random,
+                             ProtocolFamily family,
+                             int deviation,
+                             int threshold) {
+        this.random = Objects.requireNonNull(random);
+        this.history = new PortHistory(HISTORY, random);
+        this.family = family;
+        this.deviation = Math.max(1, deviation);
+        this.thresholdCount = Math.max(2, threshold);
+    }
+
+    /**
+     * Opens a datagram socket listening to the wildcard address on a
+     * random port. If the underlying OS supports UDP port randomization
+     * out of the box (if binding a socket to port 0 binds it to a random
+     * port) then the underlying OS implementation is used. Otherwise, this
+     * method will allocate and bind a socket on a randomly selected ephemeral
+     * port in the dynamic range.
+     * @return A new DatagramSocket bound to a random port.
+     * @throws SocketException if the socket cannot be created.
+     */
+    public synchronized DatagramSocket open() throws SocketException {
+        int lastseen = lastport;
+        DatagramSocket s;
+
+        boolean thresholdCrossed = unsuitablePortCount > thresholdCount;
+        if (thresholdCrossed) {
+            // Underlying stack does not support random UDP port out of the box.
+            // Use our own algorithm to allocate a random UDP port
+            s = openRandom();
+            if (s != null) return s;
+
+            // couldn't allocate a random port: reset all counters and fall
+            // through.
+            unsuitablePortCount = 0; suitablePortCount = 0; lastseen = 0;
+        }
+
+        // Allocate an ephemeral port (port 0)
+        s = openDefault();
+        lastport = s.getLocalPort();
+        if (lastseen == 0) {
+            history.offer(lastport);
+            return s;
+        }
+
+        thresholdCrossed = suitablePortCount > thresholdCount;
+        boolean farEnough = Integer.bitCount(lastseen ^ lastport) > BIT_DEVIATION
+                            && Math.abs(lastport - lastseen) > deviation;
+        boolean recycled = history.contains(lastport);
+        boolean suitable = (thresholdCrossed || farEnough && !recycled);
+        if (suitable && !recycled) history.add(lastport);
+
+        if (suitable) {
+            if (!thresholdCrossed) {
+                suitablePortCount++;
+            } else if (!farEnough || recycled) {
+                unsuitablePortCount = 1;
+                suitablePortCount = thresholdCount/2;
+            }
+            // Either the underlying stack supports random UDP port allocation,
+            // or the new port is sufficiently distant from last port to make
+            // it look like it is. Let's use it.
+            return s;
+        }
+
+        // Undecided... the new port was too close. Let's allocate a random
+        // port using our own algorithm
+        assert !thresholdCrossed;
+        DatagramSocket ss = openRandom();
+        if (ss == null) return s;
+        unsuitablePortCount++;
+        s.close();
+        return ss;
+    }
+
+    private DatagramSocket openDefault() throws SocketException {
+        if (family != null) {
+            try {
+                DatagramChannel c = DatagramChannel.open(family);
+                try {
+                    DatagramSocket s = c.socket();
+                    s.bind(null);
+                    return s;
+                } catch (Throwable x) {
+                    c.close();
+                    throw x;
+                }
+            } catch (SocketException x) {
+                throw x;
+            } catch (IOException x) {
+                SocketException e = new SocketException(x.getMessage());
+                e.initCause(x);
+                throw e;
+            }
+        }
+        return new DatagramSocket();
+    }
+
+    synchronized boolean isUsingNativePortRandomization() {
+        return  unsuitablePortCount <= thresholdCount
+                && suitablePortCount > thresholdCount;
+    }
+
+    synchronized boolean isUsingJavaPortRandomization() {
+        return unsuitablePortCount > thresholdCount ;
+    }
+
+    synchronized boolean isUndecided() {
+        return !isUsingJavaPortRandomization()
+                && !isUsingNativePortRandomization();
+    }
+
+    private DatagramSocket openRandom() {
+        int maxtries = MAX_RANDOM_TRIES;
+        while (maxtries-- > 0) {
+            int port = EphemeralPortRange.LOWER
+                    + random.nextInt(EphemeralPortRange.RANGE);
+            try {
+                if (family != null) {
+                    DatagramChannel c = DatagramChannel.open(family);
+                    try {
+                        DatagramSocket s = c.socket();
+                        s.bind(new InetSocketAddress(port));
+                        return s;
+                    } catch (Throwable x) {
+                        c.close();
+                        throw x;
+                    }
+                }
+                return new DatagramSocket(port);
+            } catch (IOException x) {
+                // try again until maxtries == 0;
+            }
+        }
+        return null;
+    }
+
+}
--- a/src/jdk.naming.dns/share/classes/com/sun/jndi/dns/DnsClient.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/jdk.naming.dns/share/classes/com/sun/jndi/dns/DnsClient.java	Fri Jan 12 15:05:35 2018 -0800
@@ -85,7 +85,9 @@
     private int timeout;                // initial timeout on UDP queries in ms
     private int retries;                // number of UDP retries
 
-    private DatagramSocket udpSocket;
+    private final Object udpSocketLock = new Object();
+    private static final DNSDatagramSocketFactory factory =
+            new DNSDatagramSocketFactory(random);
 
     // Requests sent
     private Map<Integer, ResourceRecord> reqs;
@@ -105,14 +107,6 @@
             throws NamingException {
         this.timeout = timeout;
         this.retries = retries;
-        try {
-            udpSocket = new DatagramSocket();
-        } catch (java.net.SocketException e) {
-            NamingException ne = new ConfigurationException();
-            ne.setRootCause(e);
-            throw ne;
-        }
-
         this.servers = new InetAddress[servers.length];
         serverPorts = new int[servers.length];
 
@@ -142,6 +136,16 @@
         resps = Collections.synchronizedMap(new HashMap<Integer, byte[]>());
     }
 
+    DatagramSocket getDatagramSocket() throws NamingException {
+        try {
+            return factory.open();
+        } catch (java.net.SocketException e) {
+            NamingException ne = new ConfigurationException();
+            ne.setRootCause(e);
+            throw ne;
+        }
+    }
+
     @SuppressWarnings("deprecation")
     protected void finalize() {
         close();
@@ -151,7 +155,6 @@
     private Object queuesLock = new Object();
 
     public void close() {
-        udpSocket.close();
         synchronized (queuesLock) {
             reqs.clear();
             resps.clear();
@@ -393,43 +396,45 @@
 
         int minTimeout = 50; // msec after which there are no retries.
 
-        synchronized (udpSocket) {
-            DatagramPacket opkt = new DatagramPacket(
-                    pkt.getData(), pkt.length(), server, port);
-            DatagramPacket ipkt = new DatagramPacket(new byte[8000], 8000);
-            // Packets may only be sent to or received from this server address
-            udpSocket.connect(server, port);
-            int pktTimeout = (timeout * (1 << retry));
-            try {
-                udpSocket.send(opkt);
+        synchronized (udpSocketLock) {
+            try (DatagramSocket udpSocket = getDatagramSocket()) {
+                DatagramPacket opkt = new DatagramPacket(
+                        pkt.getData(), pkt.length(), server, port);
+                DatagramPacket ipkt = new DatagramPacket(new byte[8000], 8000);
+                // Packets may only be sent to or received from this server address
+                udpSocket.connect(server, port);
+                int pktTimeout = (timeout * (1 << retry));
+                try {
+                    udpSocket.send(opkt);
 
-                // timeout remaining after successive 'receive()'
-                int timeoutLeft = pktTimeout;
-                int cnt = 0;
-                do {
-                    if (debug) {
-                       cnt++;
-                        dprint("Trying RECEIVE(" +
-                                cnt + ") retry(" + (retry + 1) +
-                                ") for:" + xid  + "    sock-timeout:" +
-                                timeoutLeft + " ms.");
-                    }
-                    udpSocket.setSoTimeout(timeoutLeft);
-                    long start = System.currentTimeMillis();
-                    udpSocket.receive(ipkt);
-                    long end = System.currentTimeMillis();
+                    // timeout remaining after successive 'receive()'
+                    int timeoutLeft = pktTimeout;
+                    int cnt = 0;
+                    do {
+                        if (debug) {
+                           cnt++;
+                            dprint("Trying RECEIVE(" +
+                                    cnt + ") retry(" + (retry + 1) +
+                                    ") for:" + xid  + "    sock-timeout:" +
+                                    timeoutLeft + " ms.");
+                        }
+                        udpSocket.setSoTimeout(timeoutLeft);
+                        long start = System.currentTimeMillis();
+                        udpSocket.receive(ipkt);
+                        long end = System.currentTimeMillis();
 
-                    byte[] data = ipkt.getData();
-                    if (isMatchResponse(data, xid)) {
-                        return data;
-                    }
-                    timeoutLeft = pktTimeout - ((int) (end - start));
-                } while (timeoutLeft > minTimeout);
+                        byte[] data = ipkt.getData();
+                        if (isMatchResponse(data, xid)) {
+                            return data;
+                        }
+                        timeoutLeft = pktTimeout - ((int) (end - start));
+                    } while (timeoutLeft > minTimeout);
 
-            } finally {
-                udpSocket.disconnect();
+                } finally {
+                    udpSocket.disconnect();
+                }
+                return null; // no matching packet received within the timeout
             }
-            return null; // no matching packet received within the timeout
         }
     }
 
--- a/src/jdk.naming.dns/share/classes/com/sun/jndi/dns/ResourceRecord.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/jdk.naming.dns/share/classes/com/sun/jndi/dns/ResourceRecord.java	Fri Jan 12 15:05:35 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -355,8 +355,19 @@
                     pos += typeAndLen;
                 } else if ((typeAndLen & 0xC0) == 0xC0) { // name compression
                     ++level;
-                    endPos = pos + 2;
+                    // cater for the case where the name pointed to is itself
+                    // compressed: we don't want endPos to be reset by the second
+                    // compression level.
+                    int ppos = pos;
+                    if (endPos == -1) endPos = pos + 2;
                     pos = getUShort(pos) & 0x3FFF;
+                    if (debug) {
+                        dprint("decode: name compression at " + ppos
+                                + " -> " + pos + " endPos=" + endPos);
+                        assert endPos > 0;
+                        assert pos < ppos;
+                        assert pos >= Header.HEADER_SIZE;
+                    }
                 } else
                     throw new IOException("Invalid label type: " + typeAndLen);
             }
@@ -405,6 +416,11 @@
             }
         }
         // Unknown RR type/class
+        if (debug) {
+            dprint("Unknown RR type for RR data: " + rrtype + " rdlen=" + rdlen
+                   + ", pos=" + pos +", msglen=" + msg.length + ", remaining="
+                   + (msg.length-pos));
+        }
         byte[] rd = new byte[rdlen];
         System.arraycopy(msg, pos, rd, 0, rdlen);
         return rd;
@@ -613,4 +629,15 @@
 
         return sb.toString();
     }
+
+    //-------------------------------------------------------------------------
+
+    private static final boolean debug = false;
+
+    private static void dprint(String mess) {
+        if (debug) {
+            System.err.println("DNS: " + mess);
+        }
+    }
+
 }
--- a/src/jdk.security.auth/share/classes/com/sun/security/auth/module/LdapLoginModule.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/src/jdk.security.auth/share/classes/com/sun/security/auth/module/LdapLoginModule.java	Fri Jan 12 15:05:35 2018 -0800
@@ -737,7 +737,8 @@
 
         if (authFirst || authOnly) {
 
-            String id = replaceUsernameToken(identityMatcher, authcIdentity);
+            String id =
+                replaceUsernameToken(identityMatcher, authcIdentity, username);
 
             // Prepare to bind using user's username and password
             ldapEnvironment.put(Context.SECURITY_CREDENTIALS, password);
@@ -864,8 +865,13 @@
         }
 
         try {
-            NamingEnumeration<SearchResult> results = ctx.search("",
-                replaceUsernameToken(filterMatcher, userFilter), constraints);
+            // Sanitize username and substitute into LDAP filter
+            String canonicalUserFilter =
+                replaceUsernameToken(filterMatcher, userFilter,
+                    escapeUsernameChars());
+
+            NamingEnumeration<SearchResult> results =
+                ctx.search("", canonicalUserFilter, constraints);
 
             // Extract the distinguished name of the user's entry
             // (Use the first entry if more than one is returned)
@@ -913,12 +919,61 @@
     }
 
     /**
+     * Modify the supplied username to encode characters that must be escaped
+     * according to RFC 4515: LDAP: String Representation of Search Filters.
+     *
+     * The following characters are encoded as a backslash "\" (ASCII 0x5c)
+     * followed by the two hexadecimal digits representing the value of the
+     * escaped character:
+     *     '*' (ASCII 0x2a)
+     *     '(' (ASCII 0x28)
+     *     ')' (ASCII 0x29)
+     *     '\' (ASCII 0x5c)
+     *     '\0'(ASCII 0x00)
+     *
+     * @return the modified username with its characters escaped as needed
+     */
+    private String escapeUsernameChars() {
+        int len = username.length();
+        StringBuilder escapedUsername = new StringBuilder(len + 16);
+
+        for (int i = 0; i < len; i++) {
+            char c = username.charAt(i);
+            switch (c) {
+            case '*':
+                escapedUsername.append("\\\\2A");
+                break;
+            case '(':
+                escapedUsername.append("\\\\28");
+                break;
+            case ')':
+                escapedUsername.append("\\\\29");
+                break;
+            case '\\':
+                escapedUsername.append("\\\\5C");
+                break;
+            case '\0':
+                escapedUsername.append("\\\\00");
+                break;
+            default:
+                escapedUsername.append(c);
+            }
+        }
+
+        return escapedUsername.toString();
+    }
+
+
+    /**
      * Replace the username token
      *
+     * @param matcher the replacement pattern
      * @param string the target string
+     * @param username the supplied username
      * @return the modified string
      */
-    private String replaceUsernameToken(Matcher matcher, String string) {
+    private String replaceUsernameToken(Matcher matcher, String string,
+        String username) {
         return matcher != null ? matcher.replaceAll(username) : string;
     }
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/hotspot/gtest/code/test_vtableStub.cpp	Fri Jan 12 15:05:35 2018 -0800
@@ -0,0 +1,52 @@
+/*
+ * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ *
+ */
+
+#include "precompiled.hpp"
+#include "code/vtableStubs.hpp"
+#include "runtime/interfaceSupport.hpp"
+#include "unittest.hpp"
+
+TEST_VM(code, vtableStubs) {
+  // Should be in VM to use locks
+  ThreadInVMfromNative ThreadInVMfromNative(JavaThread::current());
+
+  VtableStubs::find_vtable_stub(0); // min vtable index
+  for (int i = 0; i < 15; i++) {
+    VtableStubs::find_vtable_stub((1 << i) - 1);
+    VtableStubs::find_vtable_stub((1 << i));
+  }
+  VtableStubs::find_vtable_stub((1 << 15) - 1); // max vtable index
+}
+
+TEST_VM(code, itableStubs) {
+  // Should be in VM to use locks
+  ThreadInVMfromNative ThreadInVMfromNative(JavaThread::current());
+
+  VtableStubs::find_itable_stub(0); // min itable index
+  for (int i = 0; i < 15; i++) {
+    VtableStubs::find_itable_stub((1 << i) - 1);
+    VtableStubs::find_itable_stub((1 << i));
+  }
+  VtableStubs::find_itable_stub((1 << 15) - 1); // max itable index
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/hotspot/jtreg/runtime/RedefineTests/RedefineInterfaceCall.java	Fri Jan 12 15:05:35 2018 -0800
@@ -0,0 +1,83 @@
+/*
+ * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8174962
+ * @summary Redefine class with interface method call
+ * @library /test/lib
+ * @modules java.base/jdk.internal.misc
+ * @modules java.compiler
+ *          java.instrument
+ *          jdk.jartool/sun.tools.jar
+ * @run main RedefineClassHelper
+ * @run main/othervm -javaagent:redefineagent.jar -Xlog:redefine+class+update*=trace RedefineInterfaceCall
+ */
+
+import static jdk.test.lib.Asserts.assertEquals;
+
+interface I1 { default int m() { return 0; } }
+interface I2 extends I1 {}
+
+public class RedefineInterfaceCall {
+
+    public static class C implements I2 {
+        public int test(I2 i) {
+            return i.m(); // invokeinterface cpCacheEntry
+        }
+    }
+
+    static String newI1 =
+      "interface I1 { default int m() { return 1; } }";
+
+    static String newC =
+        "public class RedefineInterfaceCall$C implements I2 { " +
+        "  public int test(I2 i) { " +
+        "    return i.m(); " +
+        "  } " +
+        "} ";
+
+    static int test(I2 i) {
+        return i.m(); // invokeinterface cpCacheEntry
+    }
+
+    public static void main(String[] args) throws Exception {
+        C c = new C();
+
+        assertEquals(test(c),   0);
+        assertEquals(c.test(c), 0);
+
+        RedefineClassHelper.redefineClass(C.class, newC);
+
+        assertEquals(c.test(c), 0);
+
+        RedefineClassHelper.redefineClass(I1.class, newI1);
+
+        assertEquals(test(c),   1);
+        assertEquals(c.test(c), 1);
+
+        RedefineClassHelper.redefineClass(C.class, newC);
+
+        assertEquals(c.test(c), 1);
+    }
+}
--- a/test/hotspot/jtreg/runtime/SharedArchiveFile/serviceability/transformRelatedClasses/TransformTestCommon.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/test/hotspot/jtreg/runtime/SharedArchiveFile/serviceability/transformRelatedClasses/TransformTestCommon.java	Fri Jan 12 15:05:35 2018 -0800
@@ -63,8 +63,8 @@
                                             String parent, String child)
         throws Exception {
 
-        String parentSharedMatch = parent + " source: shared objects file";
-        String childSharedMatch =  child +  " source: shared objects file";
+        String parentSharedMatch = " " + parent + " source: shared objects file";
+        String childSharedMatch =  " " + child +  " source: shared objects file";
 
         if (entry.isParentExpectedShared)
             out.shouldContain(parentSharedMatch);
--- a/test/jaxp/javax/xml/jaxp/unittest/common/Bug6941169Test.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/test/jaxp/javax/xml/jaxp/unittest/common/Bug6941169Test.java	Fri Jan 12 15:05:35 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -364,6 +364,14 @@
 
     @Test
     public void testXPath_DOM_withServiceMech() {
+        /**
+         * This is in conflict with the test testXPath_DOM_withSM where the system
+         * default parser is used when the security manager is present. The test
+         * is therefore skipped when the security manager is present.
+         */
+        if (System.getSecurityManager() != null) {
+            return;
+        }
         final String XPATH_EXPRESSION = "/fooTest";
         System.out.println("Evaluate DOM Source;  Service mechnism is on by default;  It would try to use MyDOMFactoryImpl:");
         InputStream input = getClass().getResourceAsStream("Bug6941169.xml");
--- a/test/jdk/com/sun/crypto/provider/KeyAgreement/DHGenSecretKey.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/test/jdk/com/sun/crypto/provider/KeyAgreement/DHGenSecretKey.java	Fri Jan 12 15:05:35 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,6 +27,7 @@
  * @summary Verify that DHKeyAgreement can generate secret key
  * objects for AES algorithm
  * @author Valerie Peng
+ * @run main/othervm -Djdk.crypto.KeyAgreement.legacyKDF=true DHGenSecretKey
  */
 import java.security.*;
 import java.security.interfaces.*;
--- a/test/jdk/com/sun/crypto/provider/KeyAgreement/DHKeyAgreement2.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/test/jdk/com/sun/crypto/provider/KeyAgreement/DHKeyAgreement2.java	Fri Jan 12 15:05:35 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -26,6 +26,7 @@
  * @bug 7146728
  * @summary DHKeyAgreement2
  * @author Jan Luehe
+ * @run main/othervm -Djdk.crypto.KeyAgreement.legacyKDF=true DHKeyAgreement2
  */
 
 import java.io.*;
--- a/test/jdk/com/sun/crypto/provider/KeyAgreement/SameDHKeyStressTest.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/test/jdk/com/sun/crypto/provider/KeyAgreement/SameDHKeyStressTest.java	Fri Jan 12 15:05:35 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -26,7 +26,7 @@
  * @bug 8048819
  * @summary This test stressful verifies the assertion of "The secret keys generated
  * by all involved parties should be the same." for javax.crypto.KeyAgreement
- * @run main SameDHKeyStressTest
+ * @run main/othervm -Djdk.crypto.KeyAgreement.legacyKDF=true SameDHKeyStressTest
  */
 import java.security.AlgorithmParameterGenerator;
 import java.security.InvalidAlgorithmParameterException;
--- a/test/jdk/javax/management/remote/nonLocalAccess/NonLocalJMXRemoteTest.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/test/jdk/javax/management/remote/nonLocalAccess/NonLocalJMXRemoteTest.java	Fri Jan 12 15:05:35 2018 -0800
@@ -43,14 +43,37 @@
  * This tests the SingleEntryRegistry implemented by JMX.
  * This test is a manual test and uses JMX running on a *different* host.
  * JMX can be enabled in any Java runtime; for example:
- * login or ssh to the different host and invoke rmiregistry with arguments below.
+ *
+ * Note: Use remote host with latest JDK update release for invoking rmiregistry.
+ *
+ * Note: Test should be ran twice once using arg1 and once using arg2.
+ *
+ * login or ssh to the remote host and invoke rmiregistry with arg1.
  * It will not show any output.
- * {@code $JDK_HOME/bin/rmiregistry \
+ * Execute the test, after test completes execution, stop the server.
+ *
+ * repeat above step using arg2 and execute the test.
+ *
+ *
+ * arg1: {@code $JDK_HOME/bin/rmiregistry \
  *         -J-Dcom.sun.management.jmxremote.port=8888 \
  *         -J-Dcom.sun.management.jmxremote.local.only=false \
  *         -J-Dcom.sun.management.jmxremote.ssl=false \
  *         -J-Dcom.sun.management.jmxremote.authenticate=false
  * }
+ *
+ *
+ * replace "jmx-registry-host" with the hostname or IP address of the remote host
+ * for property "-J-Dcom.sun.management.jmxremote.host" below.
+ *
+ * arg2: {@code $JDK_HOME/bin/rmiregistry \
+ *         -J-Dcom.sun.management.jmxremote.port=8888 \
+ *         -J-Dcom.sun.management.jmxremote.local.only=false \
+ *         -J-Dcom.sun.management.jmxremote.ssl=false \
+ *         -J-Dcom.sun.management.jmxremote.authenticate=false \
+ *         -J-Dcom.sun.management.jmxremote.host="jmx-registry-host"
+ * }
+ *
  * On the first host modify the @run command above to replace "jmx-registry-host"
  * with the hostname or IP address of the different host and run the test with jtreg.
  */
@@ -123,6 +146,7 @@
             if (asIndex < 0 ||
                     disallowIndex < 0 ||
                     nonLocalHostIndex < 0 ) {
+                System.out.println("Exception message is " + msg);
                 throw new RuntimeException("exception message is malformed", t);
             }
             System.out.printf("Found expected AccessException: %s%n%n", t);
--- a/test/jdk/sun/security/pkcs11/KeyAgreement/TestDH.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/test/jdk/sun/security/pkcs11/KeyAgreement/TestDH.java	Fri Jan 12 15:05:35 2018 -0800
@@ -28,8 +28,8 @@
  * @author Andreas Sterbenz
  * @library ..
  * @modules jdk.crypto.cryptoki
- * @run main/othervm TestDH
- * @run main/othervm TestDH sm
+ * @run main/othervm -Djdk.crypto.KeyAgreement.legacyKDF=true TestDH
+ * @run main/othervm -Djdk.crypto.KeyAgreement.legacyKDF=true TestDH sm
  */
 
 import java.security.KeyPair;
--- a/test/jdk/sun/security/ssl/ClientHandshaker/RSAExport.java	Fri Jan 12 10:05:00 2018 -0800
+++ b/test/jdk/sun/security/ssl/ClientHandshaker/RSAExport.java	Fri Jan 12 15:05:35 2018 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2008, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -419,6 +419,7 @@
         // reset the security property to make sure that the algorithms
         // and keys used in this test are not disabled.
         Security.setProperty("jdk.certpath.disabledAlgorithms", "MD2");
+        Security.setProperty("jdk.tls.disabledAlgorithms", "MD2");
 
         if (debug)
             System.setProperty("javax.net.debug", "all");